Finding Inverse Matrix Function Ordering

6 visualizaciones (últimos 30 días)
Kyle Fertig
Kyle Fertig el 4 de Dic. de 2017
Respondida: Sonam Gupta el 8 de Dic. de 2017
I've created a function to find the inverse of any square matrix using the decomposition of L and U. The code looked to run fine at first, but as I tried different sizes of matrices and compared them to inverse matrix calculators online, I found that the order of the columns did not line up.
For the code shown below, when I plug in the A, L, and U of the 3x3 matrix, it works fine.
When I try a 4x4 matrix, the first and last column of the matrix are flipped around.
I assumed this meant that even length matrices would need swapped, so I made another if else statement to swap them. 3x3 and 4x4 matrices worked fine after that, but when I tried a 5x5 matrix, it was just messed up even more so I ditched the row swapping in the code posted below (though what used to be the Ainv variable is now the Atemp variable).
I'm obviously missing something bigger here, so any help is appreciated!
Thanks,
-Kyle
function Atemp = myinv(L,U,A);
%%Taking Apart Identity Matrix
w=length(L);
I=eye(w);
n=length(L);
M=cell(1,n)
for v=1:w;
b=I(:,v)
%%Gauss Elim L
n=length(L);
m=zeros(n,1);
x=zeros(n,1);
for k =1:n-1;
%compute the kth column of M
m(k+1:n) = L(k+1:n,k)/L(k,k);
%compute
%An=Mn*An-1;
%bn=Mn*bn-1;
for i=k+1:n;
L(i, k+1:n) = L(i,k+1:n)-m(i)*L(k,k+1:n);
end;
b(k+1:n)=b(k+1:n)-b(k)*m(k+1:n);
end;
W= triu(L);
%BACKWARD ELIMINATION
x(n)=b(n)/L(n,n);
for k =n-1:-1:1;
b(1:k)=b(1:k)-x(k+1)* W(1:k,k+1);
x(k)=b(k)/W(k,k);
end;
%%Gauss Elim U
n=length(U);
m=zeros(n,1);
p=zeros(n,1);
for k =1:n-1;
%compute the kth column of M
m(k+1:n) = U(k+1:n,k)/U(k,k);
%compute
%An=Mn*An-1;
%bn=Mn*bn-1;
for i=k+1:n;
U(i, k+1:n) = U(i,k+1:n)-m(i)*U(k,k+1:n);
end;
x(k+1:n)=x(k+1:n)-x(k)*m(k+1:n);
end;
W= triu(U);
%BACKWARD ELIMINATION
p(n)=x(n)/U(n,n);
for k =n-1:-1:1;
x(1:k)=x(1:k)-p(k+1)* W(1:k,k+1);
p(k)=x(k)/W(k,k)
end;
M{v}=p;
end
n=length(M);
Atemp = zeros(n);
Atemp(1);
for i=1:n;
Atemp(:,i) = M{i};
end
end
  1 comentario
John D'Errico
John D'Errico el 4 de Dic. de 2017
Without trying to read your code, odds are this is a question of pivoting. Larger matrices are more likely to involve pivoting.

Iniciar sesión para comentar.

Respuestas (1)

Sonam Gupta
Sonam Gupta el 8 de Dic. de 2017

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by