LU分解Crout减少

时间:2015-04-04 19:44:00

标签: matlab scilab reduction

这是我的LU Decomposition Crout Method的代码:

function [L, U] = croutreduction(A)
    [row,column]=size(A);
    L=eye(row,column);

    //A = 3x3
    if row==3 then
        U(1,1)=A(1,1); U(1,2)=A(1,2); U(1,3)=A(1,3);
        L(2,1)=A(2,1)/U(1,1); L(3,1)=A(3,1)/U(1,1);

        U(2,2)=A(2,2)-L(2,1)*U(1,2);
        U(2,3)=A(2,3)-L(2,1)*U(1,3);
        L(3,2)=A(3,2)/U(2,2);

        U(3,3)=A(3,3)-L(3,2)*U(2,3);    
    end

    //A = 4x4
    if column==4 then
        U(1,1)=A(1,1); U(1,2)=A(1,2); U(1,3)=A(1,3); U(1,4)=A(1,4);
        L(2,1)=A(2,1)/U(1,1); L(3,1)=A(3,1)/U(1,1); L(4,1)=A(4,1)/U(1,1);

        U(2,2)=A(2,2)-L(2,1)*U(1,2);
        U(2,3)=A(2,3)-L(2,1)*U(1,3);
        U(2,4)=A(2,4)-L(2,1)*U(1,4);
        L(3,2)=(A(3,2)-L(3,1)*U(1,2))/U(2,2);
        L(4,2)=(A(4,2)-L(4,1)*U(1,2))/U(2,2);

        U(3,3)=A(3,3)-(L(3,1)*U(1,3)+L(3,2)*U(2,3));  
        U(3,4)=A(3,4)-(L(3,1)*U(1,4)+L(3,2)*U(2,4));  
        L(4,3)=(A(4,3)-(L(4,1)*U(1,3)+L(4,2)*U(2,3)))/U(3,3);

        U(4,4)=A(4,4)-(L(4,1)*U(1,4)+L(4,2)*U(2,4)+L(4,3)*U(3,4));
    end   
endfunction

如何修改我的代码以使用不同维度的矩阵?如您所见,上面的代码仅适用于3x3和4x4矩阵。

1 个答案:

答案 0 :(得分:1)

您应该使用for循环而不是硬编码索引。基于这个例子:http://en.wikipedia.org/wiki/Crout_matrix_decomposition我修改了Scilab的代码(原始代码用于C和Matlab / Octave):

function [L,U]=LUdecompCrout(A)
  [r,c]=size(A);
  for i=1:r
    L(i,1)=A(i,1);
    U(i,i)=1;
  end
  for j=2:r
    U(1,j)=A(1,j)/L(1,1);
  end
  for i=2:r
    for j=2:i
      L(i,j)=A(i,j)-L(i,1:j-1)*U(1:j -1,j);
    end

    for j=i+1:r
      U(i,j)=(A(i,j)-L(i,1:i-1)*U(1:i-1,j))/L(i,i);
    end
  end
endfunction

Hovewer这给出了与你的代码不同的结果,我没有检查哪一个是错的,哪里......