简体   繁体   English

如何创建一个numpy矩阵,其值满足几个条件?

[英]How to create a numpy matrix, whose values meet several conditions?

I want to create a matrix, that meets this condition at first: 我想创建一个符合这种条件的矩阵:

  1. eg if a value m[2][1] == 0 <-> m[1][2] in {0,1} 例如,如果m[1][2] in {0,1}的值为m[2][1] == 0 < - > m[1][2] in {0,1}

For this one I use an upper triangular matrix like: 对于这个,我使用上三角矩阵,如:

m = np.ones((6, 6), int)
m = np.triu(m, 1)

And I change some random values of the remaining to zero, until a certain percentage is achieved: 并且我将剩余的一些随机值更改为零,直到达到一定百分比:

MaxPer = 0.75   
i, e = np.count_nonzero(m), np.count_nonzero(m)
MAX = np.round(MaxPre*e)
while i > MAX:
   m[np.random.randint(len(m[0][:]))][np.random.randint(len(m[0][:]))] = 0
   i = np.count_nonzero(m)

Now the second criteria is the one I am struggling with: 现在第二个标准是我正在努力的标准:

  1. if m[1][2] == 1 & m[1][3] == 0 <-> m[2][3] == 0 如果m[1][2] == 1 & m[1][3] == 0 < - > m[2][3] == 0

I want to check, if all values in m satisfy this condition (indices 1,2,3 are examples). 我想检查一下,如果m所有值都满足这个条件(索引1,2,3是例子)。 If not, I want to change the value of m[2][3] to zero. 如果没有,我想将m[2][3]的值更改为零。 I tried the following code with for-loops, but it overwrites all the values to zero. 我尝试使用for循环的以下代码,但它将所有值覆盖为零。

for k in range(len(m[0][:])):
            for l in range(k, len(m[0][:])):
                for j in range(l,len(m[0][:])):
                    if matrix[k][l] == 1 & matrix[k][j] == 0:
                        matrix[l][j] = 0

Is there a simple way to this without the loops? 没有循环,有一个简单的方法吗?

I think imposing your second condition indeed causes zeroing of the matrix. 我认为强加你的第二个条件确实会导致矩阵归零。 Are you sure you want 你确定要吗?

m[i][j] == 1 & m[i][k] == 0 <-> m[j][k] == 0

without any dependencies between i, j, and k? i,j和k之间没有任何依赖关系?

Maybe you want something like this (which would require a few changes in the fors)? 也许你想要这样的东西(这需要在fors中做一些改变)?

m[i][i+1] == 1 & m[i][i+2] == 0 <-> m[i+1][i+2] == 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM