Problem substituting a for loop with vectorization
조회 수: 2 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
채택된 답변
Voss
2023년 10월 24일
% 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
추가 답변 (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!