For loop optimization in matrix operations

2 次查看(过去 30 天)
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
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
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