首页 > 解决方案 > 在numpy循环中,对矩阵的元素进行算术运算

问题描述

我正在尝试使用高斯方法在 Python 中创建计算算法。方法如下。我们制作了一个系数矩阵,包括自由项。然后我们将矩阵简化为三角形。为此,首先我们将每个元素除以沿第一列(索引为 0)的对角线 (a0,0)(在示例中为 3,8),计算索引 m,然后根据公式:它的每个元素(不包括最后一列的自由成员元素)减去它上面的元素(从零行开始)与第二行的索引 m 的乘积。另外,我们将使用免费会员的列(这里算法不重要)。

接下来,应该对第三行元素执行类似的操作(但假设在第一次迭代中,第二行的元素通过上述算法进行变换,并且将从第二列计算系数 m:因此,我们将其所有元素除以第二行 a1, 1) 的对角线元素(在示例中为 1,3)。问题:我计算了列向量 m:m = ([1,000, 1,684, 0.632])

现在我们需要处理矩阵的第二行。这就是索引的困难。首先,我不能遍历 m 的值,它的类型是浮点数。其次,我第二行的元素的索引设置错误(其实在零行之后,就是第一行)

import numpy as np
matrix = np.array([[3.8, 6.7, -1.2, 5.2], 
                   [6.4, 1.3, -2.7, 3.8], 
                   [2.4, -4.5, 3.5, -0.6]])
def gaussFunc(matrix):
    # the calculation of len1 (3) and len2 (4) is not given here
    # calculation code m for the null column:
    for row in range(len1):
        for column in range(len2-3):
            m = matrix[row][column] / matrix[column][column]
    elem = row-1                # the values of the columns on the zero row are put in the variable elem  
                                
    for i in range(len(m)-1):   # loop over a range of three values of m minus the last third: catching 
                                   # an error on len for float
                                 
        while row < (len1-1):   # while the line is the first or second (in len2 there are only 3 of 
                                  # them)
             while column < (len2-1):  # as long as the column is first, second, or third 
                                        # (minus the free member column):
                 # recalculated coefficients of the second (first in numpy) row:
                 # current element minus m for this row*top element in this column (from row 0)
                 a = matrix[row][column] - m[i]*matrix[elem][column] 

标签: pythonnumpymathmatrix

解决方案


推荐阅读