You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Octave中正确调用高斯约旦(Gauss Jordan)法处理矩阵?

在Octave中实现高斯约旦法的正确方式

问题根源

你代码中调用的Gaussian(A)是错误的——Octave没有内置这个函数,这是导致运行失败的直接原因。下面提供两种可行的实现方案:


方案1:使用Octave内置的rref函数

高斯约旦消元的核心是将矩阵转化为行最简形(Reduced Row Echelon Form),Octave内置的rref函数正好实现了这一功能。如果是解线性方程组 (Ax = B),需要先构造增广矩阵,再用rref处理:

A = [1 -2 -1; -1 1 1; 1 1 5];
B = [1; 4; -3];

# 构造增广矩阵 [A | B]
augmented_matrix = [A, B];

# 用rref执行高斯约旦消元,得到行最简形
reduced_form = rref(augmented_matrix);

# 提取方程组的解(最后一列)
solution = reduced_form(:, end);

# 可选:以分数形式显示结果
format rat
disp(solution);

运行后会直接得到方程组的解,同时reduced_form的前n列(n是A的列数)就是A经过高斯约旦消元后的行最简形。


方案2:手动实现高斯约旦法函数

如果需要自己编写高斯约旦消元的逻辑,可以定义如下函数:

function [reduced_mat] = gauss_jordan(mat)
  [m, n] = size(mat);
  
  for col = 1:min(m, n)
    # 寻找当前列的主元(绝对值最大的行)
    pivot_row = col + find(abs(mat(col:m, col)) == max(abs(mat(col:m, col))), 1) - 1;
    
    # 交换主元行与当前行
    if pivot_row ~= col
      mat([col, pivot_row], :) = mat([pivot_row, col], :);
    end
    
    # 如果主元为0,说明该列线性相关,跳过
    if mat(col, col) == 0
      continue;
    end
    
    # 将主元行归一化,使主元为1
    mat(col, :) = mat(col, :) / mat(col, col);
    
    # 消去其他行的当前列元素
    for row = 1:m
      if row ~= col && mat(row, col) ~= 0
        mat(row, :) = mat(row, :) - mat(row, col) * mat(col, :);
      end
    end
  end
  
  reduced_mat = mat;
endfunction

调用这个函数的方式如下:

A = [1 -2 -1; -1 1 1; 1 1 5];
B = [1; 4; -3];
augmented_matrix = [A, B];

# 调用自定义的高斯约旦函数
result = gauss_jordan(augmented_matrix);

# 提取解
solution = result(:, end);
format rat
disp(solution);

内容的提问来源于stack exchange,提问作者Filipe Cruz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 07:50:50