Vectorizing loop over multidimensional data
Show older comments
I would like to increase the speed of the following code as it is currently a bottleneck in a piece of software that I am developing. As can be seen, I have vectorized the code over the "M" dimension but I haven't had much luck with getting rid of the loop over W. Ultimately, the code should result in a row vector the size of W containing the summed terms shown in the second-to-last line.
For brevity, I've replaced my real data with random data.
Any assistance with further vectorizing this code or other recommendations for making it more computationally efficient are greatly appreciated.
W = -599:2:500;
numW = length(W);
Wp = 500;
M = 200;
U = rand(M,1);
V = rand(M,1);
X = rand(M,1);
Y = rand(M,1);
K = rand(M,1);
Ep = rand(M,M);
En = rand(M,M);
% Loop over W terms
WSUM = zeros(1,numW);
tic
% Precompute L terms that are invariant under the loop
L1 = U*V.'; % M x M
L2 = (K*K.').^(-1/2); % M x M
L5 = exp(1i*K.'*Wp); % 1 x M
% Precompute Q terms that are invariant under the loop
Q1 = U*V.'; % M x M
Q2 = X*Y.'; % M x M
Q3 = K*K.'; % M x M
QQ1 = (Q1 - (Q2./Q3)).*Ep; % M x M
QQ2 = (Q1 + (Q2./Q3)).*En; % M x M
% Combine Q terms
QQ = QQ1 + QQ2; % M x M
for wi = 1:numW
L3 = W(wi)^(-1/2); % 1 x 1 scalar
L4 = exp(1i*K.'*W(wi)); % 1 x M
% Combine L terms
LL = (L1.*L2.*L3).*(L4.'*L5); % M x M
% combine L and Q terms
WW = (LL.*QQ); % M x M
% Compute sum
WSUM(wi) = sum(WW,'all'); % sum terms
end % end for loop
toc
4 Comments
dpb
on 1 May 2021
As you've written it, only
L3 = W(wi)^(-1/2); % 1 x 1 scalar
L4 = exp(1i*K.'*W(wi)); % 1 x M
are not invariant inside the loop -- and they can be computed first and then just referenced.
I've not tried to factor out all the constants and figure out the algebra in the end, but looks like probably simply a summation over the array could be worked and eliminate the loop entirely.
CW Edwards
on 1 May 2021
dpb
on 1 May 2021
Have you just moved everything that isn't dependent upon the loop index out of the loop? Not doing all the other work over and over should be a noticeable savings unless the JIT compiler is smart enough to be able to recognize and cache results.
CW Edwards
on 1 May 2021
Accepted Answer
More Answers (0)
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!