For loop optimization in matrix operations

4 ビュー (過去 30 日間)
Morgan Blankenship
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by