Creating a loop with for loop
4 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Miguel Anliker
il 7 Nov 2019
Commentato: Rena Berman
il 12 Dic 2019
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 Commenti
Stephen23
il 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.
Risposta accettata
JESUS DAVID ARIZA ROYETH
il 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 Commenti
JESUS DAVID ARIZA ROYETH
il 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
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!