python中的行梯队

abh*_*jar 2 python forms row reduction

此代码适用于 3*3 矩阵。我需要它适用于 ant m*n 矩阵。

import numpy as np
b=np.arange(1,10).reshape(3,3)
Run Code Online (Sandbox Code Playgroud)

这会检查矩阵的形状,但仅适用于 3*3 矩阵

if b.shape[0]==b.shape[1]:
    for i in range(b.shape[0]): 
        for j in range(b.shape[1]):
            if i==1:
                b[i]=b[i-i][j]*b[i]-[b[i][j]*b[i-i]]
                i=i+1
                b[i]=b[i-i][j]*b[i]-[b[i][j]*b[i-i]]
                j=j+1
                b[i]=b[i]-[b[i-1]*(b[i][j]/b[i-1][j])]
print(b)
Run Code Online (Sandbox Code Playgroud)

小智 8

实际上,Python 中有一个内置库,名为sympy. 该函数Matrix().rref()可用于获得矩阵的简化行梯形形式。该函数的返回值包括两件事:1) 给定矩阵的简化行梯形形式和 2) 矩阵中包含主元的列的索引(请注意,列的索引为 0)。

以下是如何使用此功能的示例:

import sympy
sympy.Matrix([[1,2,3],[2,3,4]]).rref()

(Matrix([
[1, 0, -1],
[0, 1,  2]]), (0, 1))
Run Code Online (Sandbox Code Playgroud)

Matrix().rref() 你可以在这里找到它的实现。

  • sympy 库不是内置的(截至 22 年 1 月 22 日,在 python 3.10.2 中)。需要安装它。 (2认同)