2012-10-26 59 views
2

假設我有一個矩陣,像這樣:如何隨機替換對稱矩陣的元素?

data=matrix(c(1,0,0,0,0,0,1,0,0.6583,0,0,0,1,0,0,0,0.6583,0,1,0,0,0,0,0,1),nrow=5,ncol=5) 

    [,1] [,2] [,3] [,4] [,5] 
[1,] 1 0.0000 0 0.0000 0 
[2,] 0 1.0000 0 0.6583 0 
[3,] 0 0.0000 1 0.0000 0 
[4,] 0 0.6583 0 1.0000 0 
[5,] 0 0.0000 0 0.0000 1 

如何創建另一個矩陣,說「數據2」,使得其具有相同數量的非對角線非零元素爲「數據」,但在其他位置除了數據之外呢?隨機模擬的數據將是統一的(如此runif)。

+0

會不會有永遠的對角線上1秒?對於具有未知數量的非零值的普通方陣,問題是否存在? – Bitwise

+0

這是一個(模擬的)偏相關矩陣,其中我預先確定了非零非對角線元素的數量。因此,對角線上總會有1,它將是一個方形矩陣。 – 2012-10-26 06:24:07

+2

在這個問題中存在一些關鍵的未規定的限制:如果模擬矩陣包含相關性,則其必須具有介於-1和1之間的非對角線值,並且它們必須是正半定值或其他(如果我正確理解「偏相關」 )必須是這種矩陣的投影(通過清零一些條目對來創建)。另外,「統一」了什麼參數? (有很多方法可以參數化這些矩陣。) – whuber

回答

0

沒有真正理解這個問題。在這個例子中有兩個非對角元素和非零元素(0.6583),對嗎?在這種情況下,矩陣是否包含兩個元素?

data=matrix(c(1,0,0,0,0,0,1,0,0.6583,0,0,0,1,0,0,0,0.6583,0,1,0,0,0,0,0,1),nrow=5,ncol=5) 

# Convert to vector 
data2 <- as.numeric(data) 

# Remove diagonal 
data2 <- data2[as.logical(upper.tri(data) | lower.tri(data))] 

# Remove 0 elements 
data2 <- data2[data2 != 0] 

data2 
+1

對不起,我應該澄清。基本上在索引[2,4]或[4,2]上有一個非零非對角元素。我希望「data2」在其索引[2,4]或[4,2]以外的任何位置的矩陣中也有一個非零非對角線元素。這更清楚嗎? – 2012-10-26 06:27:36

1

這是一個有點笨拙的做法。它適用於小型矩陣,但如果要將其用於某些非常高維的問題,速度會太慢。

# Current matrix: 
data=matrix(c(1,0,0,0,0,0,1,0,0.6583,0,0,0,1,0,0,0,0.6583,0,1,0,0,0,0,0,1),nrow=5,ncol=5) 

# Number of nonzero elements in upper triangle: 
no.nonzero<-sum(upper.tri(data)*data>0) 

# Generate same number of new nonzero correlations: 
new.cor<-runif(no.nonzero,-1,1) 

# Create new diagonal matrix: 
p<-dim(data)[1] 
data2<-diag(1,p,p) 

### Insert nonzero correlations: ### 

# Step 1. Identify the places where the nonzero elements can be placed: 

pairs<-(p^2-p)/2 # Number of element in upper triangle 
combinations<-matrix(NA,pairs,2) # Matrix containing indices for those elements (i.e. (1,2), (1,3), ... (2,3), ... and so on) 

k<-0 
for(i in 1:(p-1)) 
{ 
    for(j in {i+1}:p) 
    { 
     k<-k+1 
     combinations[k,]<-c(i,j) 
    } 
} 

# Step 2. Randomly pick indices: 

places<-sample(1:k,no.nonzero) 

# Step 3. Insert nonzero correlations: 

for(i in 1:no.nonzero) 
{ 
    data2[combinations[places[i],1],combinations[places[i],2]]<-data2[combinations[places[i],2],combinations[places[i],1]]<-new.cor[i] 
} 
+0

如果你想避免位置[2,4]被重複,你可以簡單地從'組合'中刪除這些索引 –