Creating a loop with for loop

2 views (last 30 days)
How do you loop A11-A33 correctly?
function [determinant , inverse ] = invanddet3by3(A)
A11 = invanddet2by2sol(A([2,3], [2,3])); % Cofactors 3x3 matrix A
A12 = -invanddet2by2sol(A([2,3], [1,3]));
A13 = invanddet2by2sol(A([2,3], [1,2]));
A21 = -invanddet2by2sol(A([1,3], [2,3]));
A22 = invanddet2by2sol(A([1,3], [1,3]));
A23 = -invanddet2by2sol(A([1,3], [1,2]));
A31 = invanddet2by2sol(A([1,2], [2,3]));
A32 = -invanddet2by2sol(A([1,2], [1,3]));
A33 = invanddet2by2sol(A([1,2], [1,2]));
D = [A11 A12 A13; A21 A22 A23; A31 A32 A33]; % Adju Matrix
determinant = A(1,1) * A11 + A(1,2) * A12 + A(1,3) * A13; % Deter of A
if determinant == 0
inverse=[];
else
inverse = D' / determinant; % Inv of A
end
end
  4 Comments
Stephen23
Stephen23 on 7 Nov 2019
"I have to create a loop so that code lines 2-10 are simplified"
Then don't use numbered variables.
Using numbered variables is a sign that you are doing something wrong.
Rena Berman
Rena Berman on 12 Dec 2019
(Answers Dev) Restored edit

Sign in to comment.

Accepted Answer

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH on 7 Nov 2019
solution:
function [determinant , inverse ] = invanddet3by3(A)
D=zeros(3);
s=[2 3; 1 3; 1 2];
for k=1:size(D,1)
for j=1:size(D,2)
D(k,j)=(-2*mod(k+j,2)+1)*invanddet2by2sol(A(s(k,:),s(j,:)));
end
end
determinant=sum(A(1,:).*D(1,:));
if determinant == 0
inverse=[];
else
inverse = D' / determinant; % Inv of A
end
end
  3 Comments
JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH on 7 Nov 2019
yes, it is even possible to eliminate the for cycle, and receive any dimension input, basically if the sum of the row and the column gives odd then it is multiplied by -1 otherwise multiplied by 1 ((-2 * mod (k + j, 2) +1 ) -> 2x-1 --> if x==1 then y=1 else if x==0 then y=-1), I also noticed that the number 1 corresponds [2,3], the number 2 corresponds [1,3] and so on
Rik
Rik on 7 Nov 2019
Comment posted as answer by Miguel Anliker:
Thank you for the explanation.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!