Creating a loop with for loop
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Miguel Anliker
el 7 de Nov. de 2019
Comentada: Rena Berman
el 12 de Dic. de 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 comentarios
Stephen23
el 7 de Nov. de 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.
Respuesta aceptada
JESUS DAVID ARIZA ROYETH
el 7 de Nov. de 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 comentarios
JESUS DAVID ARIZA ROYETH
el 7 de Nov. de 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
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!