Creating a loop with for loop
조회 수: 2 (최근 30일)
이전 댓글 표시
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
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.
채택된 답변
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
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!