Problem substituting a for loop with vectorization

2 visualizaciones (últimos 30 días)
Kerman Bilbao Pinedo
Kerman Bilbao Pinedo el 24 de Oct. de 2023
Comentada: Voss el 25 de Oct. de 2023
I'm trying to speed up my code and I've been replacing a few for loops with arrays. However, I'm having trouble with this one and I'm not sure if it can be done the same way. The problem is that I need to calculate matrices, so when I introduce the arrays, instead of obtaining several matrices (one for each member of the array), I obtain only one giant matrix.
This is my current code:
for k1 = 0:(1*pi/180):(360*pi/180)
for k2 = 0:(1*pi/180):(360*pi/180)
JS = [
-l1*cos(k1 + alfa1) l1*sin(k1 + alfa1) ;
l2*cos(k2 + alfa2) l2*sin(k2 + alfa2)
];
JE = [
-sbr4.l1*cos(k1) 0 ;
0 -sbr4.l2*cos(k2)
];
js = det(JS);
je = det(JE);
if js == 0
% (...)
end
if je == 0
% (...)
end
end
end
And this is what I want:
k1 = linspace(0,360*pi/180,360);
k2 = linspace(0,360*pi/180,360);
K1 = repmat(k1,numel(k1),1);
K2 = repmat(transpose(k2),1,numel(k2));
JS = [
-l1*cos(K1 + alfa1) l1*sin(K1 + alfa1) ;
l2*cos(K2 + alfa2) l2*sin(K2 + alfa2)
];
JE = [
-l1*cos(K1) zeros(size(K1)) ;
zeros(size(K1)) -l2*cos(K2)
];
js = det(JS);
je = det(JE);
if js == 0
% (...)
end
if je == 0
% (...)
end
The image to the left is what the first code gives me, which is what I want and the image to the right is what the second code gives me.
If someone shares how to solve it this way or how to speed it up using another method, I'd be grateful to know.

Respuesta aceptada

Voss
Voss el 24 de Oct. de 2023
% just to have some values to run with:
l1 = 1;
l2 = 1;
alfa1 = 0;
alfa2 = 0;
k1 = linspace(0,2*pi,360);
k2 = linspace(0,2*pi,360);
% K1 = repmat(k1,numel(k2),1);
% K2 = repmat(transpose(k2),1,numel(k1));
[K1,K2] = meshgrid(k1,k2);
% K1 and K2 are 360-by-360.
% Make them 1-by-1-by-360^2:
K1 = shiftdim(K1(:),-2);
K2 = shiftdim(K2(:),-2);
% then JS and JE are 2-by-2-by-360^2
JS = [
-l1*cos(K1 + alfa1) l1*sin(K1 + alfa1) ;
l2*cos(K2 + alfa2) l2*sin(K2 + alfa2)
];
JE = [
-l1*cos(K1) zeros(size(K1)) ;
zeros(size(K1)) -l2*cos(K2)
];
% you can calculate the determinant of each 2-by-2 matrix in JS and JE in
% a loop:
for ii = 1:size(JS,3)
js = det(JS(:,:,ii));
je = det(JE(:,:,ii));
if js == 0
% (...)
end
if je == 0
% (...)
end
end
  7 comentarios
Kerman Bilbao Pinedo
Kerman Bilbao Pinedo el 25 de Oct. de 2023
Thanks a lot, it works!
Voss
Voss el 25 de Oct. de 2023
You're welcome!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by