Python解决线性代数问题之矩阵的初等变换方法

定义一个矩阵初等行变换的类

class rowTransformation():
 
 
 array = ([[],[]])
 def __init__(self,array):
  self.array = array
 def __mul__(self, other):
  pass
 # 交换矩阵的两行
 def exchange_two_lines(self,x,y):
   a = self.array[x-1:x].copy()
   self.array[x-1:x] = self.array[y-1:y]
   self.array[y-1:y] = a
   return self.array
 # 以k不等于0乘以矩阵中的某x行
 def multiply(k,x,self):
  self.array[x-1:x] = k*self.array[x-1:x]
  return self.array
 
 # 把x行所有元的k倍加到另y行上去
 def k_mul_arr_add_arr(self,k,x,y):
  self.array[y-1:y] += k*self.array[x-1:x]
  return self.array

定义一个初等列变换的类

# 封装一个初等列变换类
class colTransformation():
 
 array = ([[],[]])
 
 def __init__(self, array):
  self.array = array
 
 def __mul__(self, other):
  pass
 
 # 交换矩阵的两列
 def exchange_two_lines(self, x, y):
   a = self.array[:, x-1:x].copy()
   self.array[:, x-1:x] = self.array[:, y-1:y]
   self.array[:, y-1:y] = a
   return self.array
 
 # 以k不等于0乘以矩阵中的某x列
 def multiply(self, k, x):
  self.array[:, x-1:x] = k*self.array[:, x-1:x]
  return self.array
 
 # 把x列所有元的k倍加到另y列上去
 def k_mul_arr_add_arr(self, k, x, y):
  self.array[:, y-1:y] += k*self.array[:, x-1:x]
  return self.array

求矩阵的秩

b = np.array([[2,-1,-1,1,2],[1,1,-2,1,4],[4,-6,2,-2,4],[3,6,-9,7,9]])
a = np.linalg.matrix_rank(b)
print(a)
3

求非齐次线性方程组的解