使用FOR循环在空矩阵python中插入元素

时间:2019-09-01 02:12:56

标签: python matrix

我正在尝试做矩阵乘法。首先,我创建了一个空矩阵C,然后使用for循环进行矩阵乘法,并将结果分配给矩阵C。

double total_score = quiz_average * 20% + assignment_average*20% + exam_average * 60%;

if (total_score <= 100 && total_score >= 90) {
    System.out.println("A");
} else if (total_score <= 89.99 && total_score >= 80) {
    System.out.println("B");
} else if (total_score <= 79.99 && total_score >= 70) {
    System.out.println("C");
} else if (total_score <= 69.99 && total_score >= 60) {
    System.out.println("D");
} else if (total_score <= 59.99 && total_score >= 0) {
    System.out.println("F");
}

我收到“列表分配索引超出范围”错误。

1 个答案:

答案 0 :(得分:1)

您需要创建C,其行数与A相同,列数与B相同。

# Matrix Multiplication
A = [[1, 2] , [3, 4]]
B = [[2, 3] , [2, 1]]
n = len(A) # No. of rows
j = len(A[0]) # No. of columns
C =[[0 for j in range(len(B[0]))] for i in range(len(A))]
for i in range(len(A)):
    for j in range(len(A[0])):
        for k in range(len(A)):
            C[i][j] = C[i][j] + A[i][k] * B[k][j]
print(C)

输出

[[6, 5], [14, 13]]

矩阵乘法可以通过

完成
import numpy as np
A = np.array([[1, 2] , [3, 4]])
B = np.array([[2, 3] , [2, 1]])
np.dot(A,B)
相关问题