简体   繁体   English

python中矩阵的元素操作

[英]element-wise operations of matrix in python

Let's say I have a matrix like so: 假设我有一个像这样的矩阵:

matrix1 = [[11,12,13,14,15,16,17],[21,22,23,24,25,26,27],[31,32,33,34,35,36,37],
            [41,42,43,44,45,46,47],[51,52,53,54,55,56,57],[61,62,63,64,65,66,67],
            [71,72,73,74,75,76,77]]

and I want to make a function that will take in two matrices and do pointwise multiplication. 我想创建一个函数,它将接收两个矩阵并进行逐点乘法。 (not using numpy) (不使用numpy)

I've seen some things on using zip but that doesn't seem to be working for me. 我已经看到使用拉链的一些东西,但这似乎并不适合我。 I think its because my list is of lists and not a single list. 我认为这是因为我的列表是列表而不是单个列表。

My code: 我的代码:

def pointwise_product(a_matrix, a_second_matrix):
    # return m[i][j] = a_matrix[i][j] x a_second_matrix[i][j]
    return [i*j for i,j in zip(a_matrix,a_second_matrix)]

Matrix1 could be plugged in as both arguments here. Matrix1可以作为两个参数插入。 a second function called display_matrix would take this function in and display each element of the lists on new lines, but that's beyond on the scope of this question. 另一个名为display_matrix的函数将接受此函数并在新行上显示列表的每个元素,但这超出了本问题的范围。

my guess is that i'll need some list comprehensions or lambda functions but I'm just too new to python to full grasp them. 我的猜测是我需要一些列表推导或lambda函数,但我对python来说太新了以至于完全掌握它们。

You will need a nested comprehension since you have a 2D list. 由于您有2D列表,因此需要嵌套理解。 You can use the following: 您可以使用以下内容:

[[i * j for i, j in zip(*row)] for row in zip(matrix1, matrix2)]

This will result in the following for your example ( matrix1 * matrix1 ): 这将导致以下示例( matrix1 * matrix1 ):

[[121, 144, 169, 196, 225, 256, 289], 
 [441, 484, 529, 576, 625, 676, 729], 
 [961, 1024, 1089, 1156, 1225, 1296, 1369], 
 [1681, 1764, 1849, 1936, 2025, 2116, 2209], 
 [2601, 2704, 2809, 2916, 3025, 3136, 3249], 
 [3721, 3844, 3969, 4096, 4225, 4356, 4489], 
 [5041, 5184, 5329, 5476, 5625, 5776, 5929]]

What about 关于什么

def pw(m1, m2):
    """
    Given two lists of lists m1 and m2 of the same size, 
    returns the point-wise multiplication of them, like matrix point-wise multiplication
    """
    m = m1[:]

    for i in range(len(m)):
        for j in range(len(m[i])):
            m[i][j] = m1[i][j]*m2[i][j]

    return m

m = [[1,2,3], [4,5,6]]
assert([[1*1, 2*2, 3*3], [4*4, 5*5, 6*6]] == pw(m,m))

Is there a reason for premature optimisation? 是否存在过早优化的原因? If yes, then use numpy. 如果是,那么使用numpy。

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

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