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

如何创建另一个矩阵,比如“data2”,使其具有与“数据”相同数量的非对角线非零元素,但位于数据中的位置以外的另一个位置?随机模拟的数据将是统一的(所以 runif)。

4

2 回答 2

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]
}
于 2012-10-26T07:12:35.583 回答
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
于 2012-10-26T05:02:24.777 回答