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

6 次查看(过去 30 天)
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 个评论
the cyclist
the cyclist 2019-9-24
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.

请先登录,再进行评论。

回答(1 个)

James Tursa
James Tursa 2019-9-24
编辑:James Tursa 2019-9-24
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.

类别

Help CenterFile Exchange 中查找有关 Graphics Object Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by