I want to do matrix multiplication of N x M and 1 x M matrix : Here is my Matrix :
N=(A,[2,9])
M=[[2,3,4],[3,4,6]]
I want to multiply each element of the first row by 2 and the second row by 9 with the M list but I didn't get any idea, I know matrix multiplication. but with NumPy, I don't know.
Note: M is a matrix and N is also a matrix.
CodePudding user response:
For multiplying to matrices - A,B with dimensions mXn and pXq respectively you must have n=p. In the given example you have a matrix M with dimensions 2x3 and another matrix with dimension 2x1 so matrix multiplication isn't possible.
I want to multiply each element of the first row by 2 and the second row by 9 with the M list but I didn't get any idea, I know matrix multiplication. but with NumPy, I don't know.
This can be done using numpy with the following code:
import numpy as np
x = np.array([2,9])
M = np.array([[2,3,4],[3,4,6]])
for i in range(x.shape[0]):
M[i] *= x[i]
and the output:
array([[ 4, 6, 8],
[27, 36, 54]])
CodePudding user response:
What you describe is not matrix multiplication, but simple row-wise multiplication. You can do it conveniently in NumPy by using broadcasting. For your example (ignoring A
, which was not explained) this means that if you shape your first matrix as a one-column matrix with two rows and multiply it with your second matrix using the normal *
operator, the first matrix will be expanded to the same shape as the second one by repeating its columns. Then element-wise multiplication will be performed between the two matrices:
import numpy as np
m1 = np.array([[2],
[9]])
m2 = np.array([[2, 3, 4],
[3, 4, 6]])
m1 * m2
array([[ 4, 6, 8],
[27, 36, 54]])