简体   繁体   English

如何根据另一个矩阵的行和列的乘积分配一个 python 矩阵?

[英]How to assign a python matrix based on the product of the row and column of another matrix?

I have a matrix M that I intend to assign based on one condition checked on another matrix Q. The python code should assign 1 if the product of i and j of Q is greater than 0.5 else that index should be assigned 0. The code for both the first matrix and the second one is below我有一个矩阵 M,我打算根据在另一个矩阵 Q 上检查的一个条件进行分配。如果Qi and j的乘积大于0.5 ,则 python 代码应分配 1,否则该索引应分配为 0。第一个矩阵和第二个矩阵都在下面

x=3
y=3
matx=[[0 for i in range(x)]for j in range(y)]
matx[0][0]=0.3
matx[0][1]=0.1
matx[0][2]=0.6
matx[1][0]=0.1
matx[1][1]=0.6
matx[1][2]=0.3
matx[2][0]=0.3
matx[2][1]=0.4
matx[2][2]=0.3
Q=matx
##check the product of the column and row of i and assign, am stuck below 
M=[[1 if ... else 0]]

Assuming I understood your question correctly, you can do it with loops by first calculating the product of each row and column, then looping through each element of the new matrix calculate the product of the row and column:假设我正确理解了您的问题,您可以通过首先计算每行和每列的乘积,然后循环遍历新矩阵的每个元素来计算行和列的乘积来使用循环:

x=3
y=3
matx=[[0 for i in range(x)]for j in range(y)]
matx[0][0]=0.3
matx[0][1]=0.1
matx[0][2]=0.6
matx[1][0]=0.1
matx[1][1]=0.6
matx[1][2]=0.3
matx[2][0]=0.3
matx[2][1]=0.4
matx[2][2]=0.3
Q=matx

# Calculate row products
row_products = []
for i in range(x):
    product = 1
    for j in range(y):
        product *= Q[i][j]
    row_products.append(product)

# Calculate column products
column_products = []
for j in range(y):
    product = 1
    for i in range(x):
        product *= Q[i][j]
    column_products.append(product)

# Calculate matrix values
M=[[0 for i in range(x)]for j in range(y)]
for i in range(x):
    for j in range(y):
        if row_products[i] * column_products[j] > 0.5:
            M[i][j] = 1

Using the prod() function from the math module you can get the row and column products of the matrix and combine (cross product) them in a list comprehension:使用数学模块中的 prod() function ,您可以获得矩阵的行积和列积,并将它们组合(叉积)在列表理解中:

Q = [[0.3, 0.1, 0.6],
     [0.1, 0.6, 0.3],
     [0.3, 0.4, 0.3]]

from math import prod

rProd = [*map(prod,Q)]         # row products
cProd = [*map(prod,zip(*Q))]   # column products
M = [int(r*c/Qij>0.5) for row,r in zip(Q,rProd) for Qij,c in zip(row,cProd)] 

print(M)
[0, 0, 0, 0, 0, 0, 0, 0, 0]

Note that even with the division by Qij (which avoids having the Qij value twice in the product), the results will all be well below 0.5请注意,即使除以 Qij(避免在乘积中出现两次 Qij 值),结果都将远低于 0.5

[r*c/Qij for row,r in zip(Q,rProd) for Qij,c in zip(row,cProd)]

[0.00054, 0.00432, 0.00162, 
 0.00162, 0.00072, 0.00324, 
 0.00108, 0.00216, 0.00648]

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

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