相应的矩阵结构

时间:2017-07-20 06:02:42

标签: python r

我正在研究连锁不平衡,软件输出如下: Figure current

我真正想要的是矩阵的相应一半以及对角线上的1,如下所示: Figure anticipated

我想知道这是否可以在R或python中轻松完成? 谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

你可以轻松地使用python和numpy:

import numpy as np

# Create the empty matrix
d = np.zeros((8,8))

# Create the upper triangular matrix
d[0,2:]=1
d[1,2]=0.839
d[1,3]=1
d[1,4:6]=0.736
d[1,6:]=0.864
d[2,3:]=1
d[3,4:]=1
d[4,5:]=1
d[5,6:]=1
d[4:6,7]=0.933
d[6,7]=0.88
print(d)


# Create the full matrix with transpose and identity matrix
dFUll = d + d.T + np.eye(8)
print(dFull)

答案 1 :(得分:0)

> library(sem)
> mat <- matrix(1:64, 8, 8)
> mat[lower.tri(mat)] <- 0
> 
> diag(mat) <- 1
> mat
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    9   17   25   33   41   49   57
[2,]    0    1   18   26   34   42   50   58
[3,]    0    0    1   27   35   43   51   59
[4,]    0    0    0    1   36   44   52   60
[5,]    0    0    0    0    1   45   53   61
[6,]    0    0    0    0    0    1   54   62
[7,]    0    0    0    0    0    0    1   63
[8,]    0    0    0    0    0    0    0    1
> mat[lower.tri(mat)] <- t(mat)[lower.tri(mat)]
> mat
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    9   17   25   33   41   49   57
[2,]    9    1   18   26   34   42   50   58
[3,]   17   18    1   27   35   43   51   59
[4,]   25   26   27    1   36   44   52   60
[5,]   33   34   35   36    1   45   53   61
[6,]   41   42   43   44   45    1   54   62
[7,]   49   50   51   52   53   54    1   63
[8,]   57   58   59   60   61   62   63    1