简体   繁体   中英

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)

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. 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.

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.

You will need a nested comprehension since you have a 2D list. 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 ):

[[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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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