Elemental matrix operations in python

Say I have a matrix like this:

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 point multiplication. (not using numpy)

I saw some things when using zip, but this does not seem to work for me. I think this is because my list consists of lists, not one list.

My code is:

 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)] 

As both arguments, Matrix1 can be connected. the second function, called display_matrix, will take this function and display each list item in new lines, but this is beyond the scope of this question.

I assume that I will need some sort of lists or lambda functions, but I'm just too new to python to fully understand them.

+7
python matrix
source share
2 answers

You will need a nested understanding, 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 lead to the following 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]] 
+6
source share

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 optimization? If so, use numpy.

0
source share

All Articles