Matrix inversion and LU Decomposition. Having issues with the for loops and how they reference inputs.

3 次查看(过去 30 天)
function output =myMatrixInversion(A)
%% Problem Setup
i=1;
n=size(A);
AInv=zeros(n,n);
L=eye(n);
I=eye(n);
%% Forward Elimination w/ Multiplier Recording
% Reminder 1: Use nested loops
% Reminder 2: Use MATLAB vector/matrix operations wherever appropriate to replace unnecessary loops and simplify your code
% Reminder 3: Do not forget to display the updated coefficient matrix at the end of each FE step
for i=1:n-1 % run through each of the rows
for j=i+1:n % run through each of the columns
A(j,i+1:n)=A(j,i+1:n)-x*A(i,i+1:n)); % take the number and divide it
L(j,i)=A(j,i)/A(i,i); %simultaneously fill in L matrix
end
fprintf('\n\nIteration #%2d:\n', i)
fprintf(' The matrix is %.4e\n', A)
end
%% Forward Substitution
% Reminder 1: Use nested loops
% Reminder 2: Use MATLAB vector/matrix operations wherever appropriate to replace unnecessary loops and simplify your code
for i=1:1:n
sum=0;
for j=(i-1):1:n
sum=sum-L(i,j)*z(i,j);
end
z(i,j)=sum/L(i,i);
end
%% Backward Substitution
% Reminder 1: Use nested loops
% Reminder 2: Use MATLAB vector/matrix operations wherever appropriate to replace unnecessary loops and simplify your code
for a=1:n
for i=n:-1:1
sum=z(i,a);
for j=(i+1):1:n
sum=sum-U(i,j)*x(j,a);
end
x(i,j)=sum/U(i,i);
end
end
%% Final Output and Display
output=[L, U, z, x];
end

回答(1 个)

Divija Aleti
Divija Aleti 2020-10-29
Hi Susanna,
I understand that you want to obtain the upper and lower triangular matrices and solve the equation 'Ax=I', to find the inverse of matrix 'A'. Do refer to the following links to get to know about the MATLAB functions that can be used to achieve this.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by