Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

element-wise operations of matrix in python

Tags:

python

matrix

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.

like image 643
Ted Mosby Avatar asked May 17 '16 12:05

Ted Mosby


People also ask

What is matrix operations in Python?

A Python matrix is a specialized two-dimensional rectangular array of data stored in rows and columns. The data in a matrix can be numbers, strings, expressions, symbols, etc. Matrix is one of the important data structures that can be used in mathematical and scientific calculations.

How do you use element-wise in Python?

multiply() technique will be used to do the element-wise multiplication of matrices in Python. The NumPy library's np. multiply(x1, x2) method receives two matrices as input and executes element-wise multiplication over them before returning the resultant matrix.

How do you access the elements of a matrix in Python?

The data elements in a matrix can be accessed by using the indexes. The access method is same as the way data is accessed in Two dimensional array.

How do you use element-wise operation in NumPy?

multiply() function is used when we want to compute the multiplication of two array. It returns the product of arr1 and arr2, element-wise.


1 Answers

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]]
like image 168
Selcuk Avatar answered Nov 03 '22 06:11

Selcuk