Creating a loop with for loop

조회 수: 2 (최근 30일)
Miguel Anliker
Miguel Anliker 2019년 11월 7일
댓글: Rena Berman 2019년 12월 12일
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
Stephen23
Stephen23 2019년 11월 7일
"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 2019년 12월 12일
(Answers Dev) Restored edit

댓글을 달려면 로그인하십시오.

채택된 답변

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH 2019년 11월 7일
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
JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH 2019년 11월 7일
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 2019년 11월 7일
Comment posted as answer by Miguel Anliker:
Thank you for the explanation.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

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