find inverse matrix using naive gaussian elimination
5 views (last 30 days)
Show older comments
Hey guys, I've been working on this assignment I found online. I have to extend my naive gaussian elimination code to find the inverse matrix. I have the nge code but don't know how to go on from there and use it to find the inverse of say M = [1 2 3; 4 5 6; 7 8 1], I know I need [M | I] and make M into I and the right hand side would be M^-1. Thanks.
if true
% function x = naive_gauss_elim(A,b)
n = length(b);
x = zeros(n,1);
% Forward elimination to get upper triangular matrix
for k = 1:n-1
for i = k+1:n
xelem = A(i,k)/A(k,k);
for j = k+1:n
A(i,j) = A(i,j)-xelem*A(k,j);
end
b(i) = b(i)-xelem*b(k);
end
end
% back sub
x(n) = b(n)/A(n,n);
for i = n-1:-1:1
s = b(i);
for j = i+1:n
s = s-A(i,j)*x(j);
end
x(i) = s/A(i,i);
end
end
Answers (1)
Andrei Bobrov
on 18 Feb 2016
Edited: Andrei Bobrov
on 18 Feb 2016
[m,n] = size(M);
A = [M, eye([m, n])];
for k = 1:m
A(k,k:end) = A(k,k:end)/A(k,k);
A([1:k-1,k+1:end],k:end) = ...
A([1:k-1,k+1:end],k:end) - A([1:k-1,k+1:end],k)*A(k,k:end);
end
out = A(:,n+1:end);
0 Comments
See Also
Categories
Find more on Naive Bayes in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!