如何在MATLAB的Cramer规则中显示列向量x?

时间:2018-09-25 07:59:08

标签: matlab

我正在尝试在MATLAB上为方矩阵编码Cramer法则。我完全理解规则,也相信代码背后的逻辑是正确的。但是,您能否检查我的结果未正确显示的地方可能是哪里呢?任何帮助,将不胜感激!谢谢:)

function x = cramer(A, b)

r = size(A, 1);
c = size(A, 2);
n = size(b, 1);


if r ~= c
    disp('Oops! Please enter a square matrix');
end 

if r == c == n

D = det(A);

if D == 0
    disp('Oops! Either, there are a family of soultions or no unique solution')
end

if D ~= 0 

result = zeros(n, 1);


        for (i = 1:n)
        A_x = A;
        A_x(:, i) = b;
        Dx = det(A_x);
        result(i,1) = Dx/D;

        end

        x = result;
end

end 



end

1 个答案:

答案 0 :(得分:0)

您的if r == c == n检查中存在错误。 表达式r == c == n可以扩展为(r == c) == n 因此,它将logical(r == c)n的值进行比较。

例如:

>> 2 == 2 == 1

ans =

logical

1

将支票改写为r == c && c == nisequal(r,c,n),您应该会很好。

编辑:您可以简化很多逻辑,例如:

function x = cramers(A, b)

if diff(size(A)) && size(A,1) == n

    D = det(A);

    if D == 0
        disp('Oops! Either, there are a family of solutions or no unique solution')
        return
    else
        result = zeros(n, 1);


        for i = 1:n
            A_x = A;
            A_x(:, i) = b;
            Dx = det(A_x);
            result(i,1) = Dx/D;

        end

        x = result;
    end
else
    disp('Dimension error')
    return
end
end