For loop optimization in matrix operations

3 views (last 30 days)
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?

Answers (1)

Steven Lord
Steven Lord on 5 Aug 2020
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 Comments
Morgan Blankenship
Morgan Blankenship on 5 Aug 2020
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 on 5 Aug 2020
z1 and z2 are supposed to be cells not matrices by the way.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!