I know the steps to multiply two matrices are as follow
Step 1: Make sure that the the number of columns in the 1st one equals the number of rows in the 2nd one.
Step 2: Multiply the elements of each row of the first matrix by the elements of each column in the second matrix.
Step 3: Add the products.
How do you do the second step?
For example
A = [[3,4,5],[5,0,6],[5,7,1]]
B = [[2,1,3],[2,6,4]]
So far I got a function to find each column for the second one
def column(B,j):
col = []
for column in B:
col.append(column[j])
return col
Next I will have to make a function that finds each row for the first one
def rows(A,i):
But then I don't know how to create a function that will multiply them together like
row(A,0) • col(B,0)
row(A,0) • col(B,1)
row(A,1) • col(B,0)
row(A,1) • col(B,1)
row(A,2) • col(B,0)
row(A,2) • col(B,1)
You should probably use numpy:
import numpy as np
np.dot(row(A,0), col(B,0))
However, assuming you don't want to use that, you could do:
def dot(arr1, arr2):
return sum([x*y for x,y in zip(arr1, arr2)])
dot(row(A,0), col(B,0))
If you insist on using lists for this....
For C = AB, you need
C_{ij} = sum(A_{ik} * B_{kj})
Here, i, j, and k are subscripts, with the first subscript denoting the row and the second denoting the column. i, j, k run over the rows and columns (ie, list indices) of the matrix, so you can just write for loops over i, j, and k.
A has 3 columns, while B has 2 rows. So your example seems to contradict the requirement stated in Step 1. Nevertheless, this might be close to what you are looking for.
In [1]: A = [[3,4,5],[5,0,6],[5,7,1]]
In [2]: B = [[2,1,3],[2,6,4]]
In [3]: [[sum(r*c for r,c in zip(row, col)) for col in B] for row in A]
Out[3]: [[25, 50], [28, 34], [20, 56]]
By the way, here is a useful trick which you might find useful: If you want to transpose a matrix, use zip(*B)
:
In [4]: zip(*B)
Out[4]: [(2, 2), (1, 6), (3, 4)]
This may be useful to you because it allows you to easily loop through the columns of B
.
Here's a worked out example:
>>> from pprint import pprint
>>> def mmul(A, B):
nr_a, nc_a = len(A), len(A[0])
nr_b, nc_b = len(B), len(B[0])
if nc_a != nr_b:
raise ValueError('Mismatched rows and columns')
return [[sum(A[i][k] * B[k][j] for k in range(nc_a))
for j in range(nc_b)] for i in range(nr_a)]
>>> A = [[1, 2, 3, 4]]
>>> B = [[1],
[2],
[3],
[4]]
>>> pprint(mmul(A, B))
[[30]]
>>> pprint(mmul(B, A), width=20)
[[1, 2, 3, 4],
[2, 4, 6, 8],
[3, 6, 9, 12],
[4, 8, 12, 16]
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.