For loop optimization in matrix operations

조회 수: 4 (최근 30일)
Morgan Blankenship
Morgan Blankenship 2020년 8월 5일
댓글: Morgan Blankenship 2020년 8월 5일
I'm trying to figure out how to optimize 3 nested for loops with matrix operations. The problem boils down to:
for ii = 1:1000
for jj = 1000
for kk = 1:100
P{ii,jj,kk} = [ exp(-1i*klz(ii,jj,kk)*d(kk)), 0 ; ...
0, exp(1i*klz(ii,jj,kk)*d(kk)) ];
end
end
end
Is there a way to do something like:
for kk = 1:100
P{:,:,kk} = [ exp(-1i*klz(:,:,kk)*d(kk)), 0 ; ...
0, exp(1i*klz(:,:,kk)*d(kk)) ];
end
with some function / method of coding it to decrease the run time?

답변 (1개)

Steven Lord
Steven Lord 2020년 8월 5일
You don't need to loop to generate the values that you multiply by +1i or -1i and pass into exp.
% Sample data
x = randn(4, 5, 6);
y = 1:6;
% Approach 1: element-wise multiplication
z1 = x.*reshape(y, 1, 1, size(x, 3));
% Approach 2: loops
z2 = zeros(size(x));
for r = 1:size(x, 1)
for c = 1:size(x, 2)
for p = 1:size(x, 3)
z2(r, c, p) = x(r, c, p)*y(p);
end
end
end
% Check
z1-z2 % Should contain all 0's or small magnitude values
  댓글 수: 2
Morgan Blankenship
Morgan Blankenship 2020년 8월 5일
well exp() will return a 1000x1000 array and then when I try to add it to P it'll throw a cat error because I'm trying to do P = [ [1000x1000], 0; 0, [1000x1000]].
Morgan Blankenship
Morgan Blankenship 2020년 8월 5일
z1 and z2 are supposed to be cells not matrices by the way.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by