Trying to write a function for the inverse of a matrix.

7 Ansichten (letzte 30 Tage)
Emily Gallagher
Emily Gallagher am 24 Sep. 2019
Bearbeitet: James Tursa am 24 Sep. 2019
Trying to solve for the inverse of matrix A. Any help would be greatly appreciated.
function X = inverse(A)
n = length(A);
X=X(:,length(X)/2+1:end );
% Gaussian elimination
for j = 1:n-1
for i = j+1:n
X(i,j) = A(i,j) / A(j,j); % row multiplier
A(i,:) = A(i,:) - X(i,j)*A(j,:);
end
end
end
  2 Kommentare
the cyclist
the cyclist am 24 Sep. 2019
What is your question?
Does your code give an error? If so, post the complete error message. If not, describe why you think you have a problem. Give an example of calling your function, that exhibits the problem.
Emily Gallagher
Emily Gallagher am 24 Sep. 2019
It's not accurately solving for the inverse.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

James Tursa
James Tursa am 24 Sep. 2019
Bearbeitet: James Tursa am 24 Sep. 2019
You are missing the part where you append the identity matrix to the right side of A before you start your Gauss elimination. So, an outline would be this based on your current design:
function X = inverse(A)
n = length(A);
A = [A,eye(n)]; % <-- Append the identity matrix on the right
% Gaussian elimination
for j = 1:n % <-- do all the columns
for i = 1:n % <-- do all the rows
if( i ~= j ) % if row number is different from column number
% your stuff goes here
end
end
end
X = A(:,n+1:end); % the inverse will be in the right side nxn block
end
I have left out one piece for you, and that is the part where you need to scale the rows so that the left nxn block is the identity. See if you can figure out how to do that. It could either be inserted somewhere appropriate inside the loops you already have, or you could write a new loop at the end to do this before you pick off the X matrix. If you are unsure how to do this, first take a look at the entire resulting A matrix and see what the left side nxn block looks like. From that, you should be able to figure out code that can scale each row so that the left side nxn block is the identity matrix.

Kategorien

Mehr zu Graphics Object Programming finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by