用基础函数写了一个matlab脚本将矩阵变成行最简式。
本代码未参考matlab自带的rref函数,完全手写
大致思路:把矩阵含有0的行放在最下面,然后下面的行减去上面的行,最后变成行最简型。
function R = My_RS(A)
%A表示输入矩阵
%R表示输出的行最简型矩阵
t = 1;
T = zeros(size(A, 1), size(A, 2));
i = 1;
while i < size(A, 2)
c = size(A, 1); flcg = 0; sf = 0; flgg = 0;
%将A进行降序排序,并且把含有0的列放在最后
A = sortrows(A, 'descend');
for j = t:size(A, 1)
v = j;
op = 0;
for k = t:size(A, 1)
if A(k, i) == 0
op = op + 1;
end
end
if A(j, i) == 0
for l = v + op:size(A, 1)
T(v, :) = A(v, :);
A(v, :) = A(l, :);
v = v + 1;
end
for w = size(A, 1) - op + 1:size(A, 1)
A(w, :) = T(w, :);
end
break
end
end
%进行行循环
for j = t:size(A, 1)
if A(j, i) == 0
c = j - 1; break
end
end
%将t行i列下的元素变为0
if c - t >= 1
for m = c:-1:t + 1
%判断是否近似
for cc = i:size(A, 2)
if abs(A(m, cc) - A(t, cc)) < 10e-10
A(m, cc) = A(t, cc);
end
end
A(m, :) = A(m, :) - (A(m, i) / A(t, i)) .* A(t, :);
end
end
%判断t行前i列是否都为0
if i > 1
for gg = i - 1:-1:1
if A(t, gg) ~= 0
flgg = 1;
break
end
end
end
if flgg == 0
%第一个元素变为1
if A(t, i) ~= 0
A(t, :) = A(t, :) / A(t, i);
end
%将t行i列上的元素变为0
if t >= 2
for v = 1:t - 1
%判断是否近似
for dd = i:size(A, 2)
if abs(A(v, dd) - A(t, dd)) < 10e-10
A(v, dd) = A(t, dd);
end
end
A(v, :) = A(v, :) - (A(v, i) / A(t, i)) .* A(t, :);
end
end
end
%判断下一列(下几列)t行下的元素是否全为0
if i < size(A, 2) && t < size(A, 1)
for f = i + 1:size(A, 2)
for s = t + 1:size(A, 1)
if A(s, f) ~= 0
flcg = 1;
break
end
end
if flcg == 1
break
else
sf = sf + 1;
end
end
end
%跳过下一列(下几列)
if flcg == 0
i = i + sf;
end
if t < size(A, 1)
t = t + 1;
else
break
end
i = i + 1;
end
%赋值结果
R = A;
end