python 矩阵乘法检查第一个矩阵的行数是否等于第二个矩阵的列数

python matrix multiplication check if number of rows of 1st matrix is equal to number of columns of 2nd matrix

我需要通过获取用户输入在 2 个矩阵之间执行矩阵乘法。下面的代码适用于乘法部分,但如果没有。第一个矩阵的行数不等于第一个。第二个矩阵的列然后它应该打印 NOT POSSIBLE 并退出。但它仍然继续添加矩阵的元素。此代码中可能有什么问题以及相同的解决方案是什么。任何帮助将不胜感激

def p_mat(M,row_n,col_n):
    for i in range(row_n):
        for j in range(col_n):
            print(M[i][j],end=" ")
        print()


def mat_mul(A_rows,A_cols,A,B_rows,B_cols,B):

    if A_cols != B_rows:
        print("NOT POSSIBLE")

    else:
        C = [[0 for i in range(B_cols)] for j in range(A_rows)]

        for i in range(A_rows) :
            for j in range(B_cols) :
                C[i][j] = 0
                for k in range(B_rows) :
                    C[i][j] += A[i][k] * B[k][j]

        p_mat(C, A_rows, B_cols)

if __name__== "__main__":


    A_rows = int(input("Enter number of rows of 1st matrix: "))
    A_cols = int(input("Enter number of columns of 1st matrix: "))
    B_rows = int(input("Enter number of rows of 2nd matrix: "))
    B_cols = int(input("Enter number of columns of 2nd matrix: "))

    ##### Initialization of matrix A and B #####

    A = [[0 for i in range(B_cols)] for j in range(A_rows)]
    B = [[0 for i in range(B_cols)] for j in range(A_rows)]





    print("Enter the elements of the 1st matrix: ")

    for i in range(A_rows):
        for j in range(A_cols):
            A[i][j] = int(input("A[" + str(i) + "][" + str(j) + "]: "))


    print("Enter the elements of the 2nd matrix: ")

    for i in range(B_rows):
        for j in range(B_cols):
            B[i][j] = int(input("B[" + str(i) + "][" + str(j) + "]:"))


    ##### Print the 1st & 2nd matrices #####

    print("First Matrix : ")
    p_mat(A,A_rows,A_cols)

    print("Second Matrix : ")
    p_mat(B,B_rows,B_cols)


    ### Function call to multiply the matrices ###

    mat_mul(A_rows,A_cols,A,B_rows,B_cols,B)

对于矩阵乘法,第一个矩阵的列数必须等于第二个矩阵的行数。

如果你想检查第一个矩阵的行数和第一个矩阵的行数。第二个矩阵的列然后将 if A_cols != B_rows 更改为 if A_rows != B_cols

使用您当前的代码,它会在 A_cols != B_rows 时打印 NOT POSSIBLE,这是正确的。 例如

Enter number of rows of 1st matrix: 2         
Enter number of columns of 1st matrix: 3
Enter number of rows of 2nd matrix: 2
Enter number of columns of 2nd matrix: 3
Enter the elements of the 1st matrix: 
A[0][0]: 1
A[0][1]: 2
A[0][2]: 3
A[1][0]: 4
A[1][1]: 5
A[1][2]: 6
Enter the elements of the 2nd matrix: 
B[0][0]:1
B[0][1]:2
B[0][2]:3
B[1][0]:4
B[1][1]:5
B[1][2]:6
First Matrix : 
1 2 3 
4 5 6 
Second Matrix : 
1 2 3 
4 5 6 
NOT POSSIBLE

代码中的另一个错误是当您初始化 Matrices.You 时正在做

A = [[0 for i in range(B_cols)] for j in range(A_rows)]
B = [[0 for i in range(B_cols)] for j in range(A_rows)]

如果在 A 中添加元素时 B_cols 小于 A_cols 将引发 IndexError 同样,如果 B_cols 大于 A_cols,当您向 B 添加元素时将引发 IndexError。 将其更改为

A = [[0 for i in range(A_cols)] for j in range(A_rows)]
B = [[0 for i in range(B_cols)] for j in range(B_rows)]