'Python Matrice multiplication
I am using a program which generates two matrices of the same shape which differ from 1 till 11 rows and always has the same amount of columns. I need to multiply these matrice cell by cell.
For example if I have:
([1 1 1];[2 2 2];[3 3 3]) * ([1 2 3]; [4 5 6]; [2 4 6]) = ([1 2 3]; [8 10 12]; [6 12 9])
I am having trouble using the A*A Could someone help me? Many thanks
Solution 1:[1]
You could try this:
arr1=[[1,1,1],[2,2,2],[3,3,3]]
arr2 = [[1,2,3],[4,5,6],[2,4,6]]
multi = lambda a,b: [[p[i]*q[i] for i in range(len(p))] for p, q in zip(a,b)]
print(multi(arr1,arr2))
Or use numpy as @BrennenSprimont's answer :
import numpy as np
first = np.array([[1,1,1],[2,2,2],[3,3,3]])
seco = np.array([[1,2,3],[4,5,6],[2,4,6]])
print(first*seco)
Solution 2:[2]
In many contexts Math folks have defined the * for matrices to mean the linear algebra "dot product". To do "element/cell wise multiplication", you need to either use numpy.multiply or use a couple for loops.
With numpy python3 -m pip install numpy
# EDIT: Don't use numpy.matrix, they are deprecated and will eventually be removed.
# Use numpy.array as seen in @MrNobody33's answer.
# left_matrix = numpy.matrix("1 1 1; 2 2 2; 3 3 3")
# right_matrix = numpy.matrix("1 2 3; 4 5 6; 7 8 9")
left_matrix = numpy.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]])
right_matrix = numpy.array([[1, 2, 3], [4, 5, 6], [2, 4, 6]])
result_matrix = numpy.multiply(left_matrix, right_matrix)
# Use * or numpy.dot for the linear algebra matrix multiplication.
print(result_matrix)
Without numpy.
left_matrix = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
right_matrix = [[1, 2, 3], [4, 5, 6], [2, 4, 6]]
result_matrix = []
for i in range(len(left_matrix)):
result_matrix.append([])
for j in range(len(left_matrix[0])):
cell_result = left_matrix[i][j] * right_matrix[i][j]
result_matrix[i].append(cell_result)
print(result_matrix)
Solution 3:[3]
Thank you for the help. I was looking for element wise multiplications and found that there was a numpy command for this. np.multiply
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Diederik Portheine |
