For loop optimization in matrix operations
1 次查看(过去 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?
0 个评论
回答(1 个)
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
另请参阅
类别
在 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!