Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multiply matrixes using for loops - Python

Tags:

python

I have no idea how to even begin doing this It needs to be a for loop to multiply mtrixes

for example

[[1,2],[3,4]] * [[3,4],[5,6]]

[1 , 2] , [3 , 4]

[3 , 4] *[5 , 6]

Need help much appreciated I know 90% of dont want to code for me so that's ok

It only needs to be two square matrixes

i'm pretty sure the pattern is looking at it in the list thing

a[1][1]*b[1][1]+a[1][2]*b[2][1]       a[1][1]b[1][2]+a[1][2]b[2][2]

a[2][1]b[1][1]+a[2][2]b[2][1]         a[2][1]b[1][2]+a[2][2]b[2][2]
like image 692
jimbob Avatar asked Nov 15 '25 17:11

jimbob


2 Answers

result = [] # final result
for i in range(len(A)):

    row = [] # the new row in new matrix
    for j in range(len(B[0])):
        
        product = 0 # the new element in the new row
        for v in range(len(A[i])):
            product += A[i][v] * B[v][j]
        row.append(product) # append sum of product into the new row
        
    result.append(row) # append the new row into the final result


print(result)
like image 109
Aaron Shen Avatar answered Nov 18 '25 06:11

Aaron Shen


Break it down. Before you try to write a function that multiplies matrices, write one that multiplies vectors. If you can do that, multiplying two matrices is just a matter of multiplying row i and column j for every element i,j of the resultant matrix.

like image 25
Caleb Avatar answered Nov 18 '25 07:11

Caleb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!