简体   繁体   English

如何使用 for 循环乘以矩阵 - Python

[英]How to multiply matrixes using for loops - Python

I have no idea how to even begin doing this It needs to be a for loop to multiply mtrixes我什至不知道如何开始这样做它需要是一个 for 循环来乘以 mtrixes

for example例如

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

[1 , 2] , [3 , 4] [1 , 2] , [3 , 4]

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

Need help much appreciated I know 90% of dont want to code for me so that's ok非常感谢需要帮助我知道 90% 的人不想为我编码,所以没关系

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]
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)

If you look at how matrix multiplication works:如果你看看矩阵乘法是如何工作的:

[ 1 2 ] x [ 5 6 ] = [ 1*5+2*7 1*6+2*8 ]
[ 3 4 ]   [ 7 8 ]   [ 3*5+4*7 3*6+4*8 ]

then you can determine a method to calculate this, eg if you are multiplying for element i , j of the output matrix, then you need to multiply everything in row i of the LHS matrix by everything in the column j of the RHS matrix, so that is a single for loop (as the number of elements in the row i is equal to column j ).那么您可以确定一种计算方法,例如,如果您要乘以输出矩阵的元素i , j ,那么您需要将 LHS 矩阵第i行中的所有内容乘以 RHS 矩阵第j列中的所有内容,所以那是一个 for 循环(因为行i 中的元素数等于列j )。

You also need to cover every combination of i and j for the dimensions of the output matrix, which is a for loop for the columns nested inside a for loop for the rows.您还需要涵盖输出矩阵维度的ij 的每个组合,这是一个 for 循环,用于嵌套在行的 for 循环中的列。

The actual code is, of course, an exercise for you to implement.当然,实际的代码是一个供您实现的练习。

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.如果你能做到这一点,那么两个矩阵相乘只是将结果矩阵的每个元素 i,j 的行 i 和列 j 相乘。

def matmul(matrix1_,matrix2_):
    result = [] # final result

    for i in range(len(matrix1_)):

        row = [] # the new row in new matrix
        for j in range(len(matrix2_[0])):

            product = 0 # the new element in the new row

            for v in range(len(matrix1_[i])):
                 product += matrix1_[i][v] * matrix2_[v][j]
            row.append(product) # append sum of product into the new row

        result.append(row) # append the new row into the final result
    return result
from numpy import *
m1 = array([[1, 2, 3],[4, 5, 6] ])
m2 = array([[7, 8],[9, 10],[11, 12]])
r = array([[0, 0],[0, 0]])
s = 0
for i in range(2):
    for j in range(2):
        for k in range(3):
            s = s + m1[i][k]*m2[k][j]

        r[i][j] = s
        s = 0
print(r)

I think append function is not working in a two-dimensional array when we are using numpy module, so this is the way I have solved it.我认为当我们使用 numpy 模块时 append 函数在二维数组中不起作用,所以这就是我解决它的方法。

>>> A=[[1,2],[3,4]]
>>> B=[[3,4],[5,6]]
>>> n=2
>>> ans=[[0]*n for i in range(n)]
>>> ans
[[0, 0], [0, 0]]
>>> for i in range(n):
...     for j in range(n):
...             ans[i][j]=sum((A[i][v]*B[v][j] for v in range(n)))
... 
>>> ans
[[13, 16], [29, 36]]

I think you just need to simplify the formula of matrix multiplication.我认为您只需要简化矩阵乘法的公式即可。

We have A*B=C then: Cij= the value in the ith row and jth column of the answer.我们有 A*B=C 那么: Cij=答案的第 i 行第 j 列中的值。 For example above we have C12=16 and C11=13.. (note that this is the 0th position in the array so often we start from 0 instead of 1)例如上面我们有 C12=16 和 C11=13..(注意这是数组中的第 0 个位置,所以我们经常从 0 开始而不是 1)

Cij= dot_product(row_i_of_A,column_j_of_B)=sum(row_i_of_A(v)*column_j_of_B(v) for v in range(n)) Cij= dot_product(row_i_of_A,column_j_of_B)=sum(row_i_of_A(v)*column_j_of_B(v) for v in range(n))

Because we want the whole answer (all of C), we need to work out all possible Cij.因为我们想要完整的答案(所有的 C),所以我们需要计算出所有可能的 Cij。 This means we need to try all possible pairs ij, so we loop through i in range(n), j in range(n) and do this for each possible pair.这意味着我们需要尝试所有可能的对 ij,因此我们在 range(n) 中遍历 i,在 range(n) 中遍历 j,并对每个可能的对执行此操作。

u and v are constructed for visualization purpose. u 和 v 是为可视化目的而构建的。

from typing import List
A = [[1,0,0],[-1,0,3]]
B = [[7,0,0],[0,0,0],[0,0,1]]

def mult_mat(A:List[List[int]], B:List[List[int]]) -> List[List[int]]:
    n = len(A)      # Number of rows in matrix A
    m = len(B[0])   # Number of columns in matrix B

    ret = [[0 for i in range(m)] for j in range(n)]

    for row in range(n):
        u = A[row]

        for col in range(m):
            v = [B[i][col] for i in range(len(B))]
            # Here you can calculate ret[row][col] directly without v
            # But v is constructed for visualization purpose
            ret[row][col] = sum([x*y for x,y in zip(u,v)])
    return ret

if __name__ == '__main__':
    print(mult_mat(A,B))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM