How to vectorize nested loops with conditional statements?
7 views (last 30 days)
Show older comments
I am trying to vectorize given code in order to speed up the performance of code. I tried with preallocation, but I am unable to resolve this. Any suggestion or correction in the given code would be appreciated.
tributary = randn([81, 126]);
cp_mesh = randn([81, 126, 49792]);
cp_B1_2 = zeros(49792,1);
for i=1:49792
temp3 = [];
for k=9:118 %k is column
if k<=117
for j=1:8 %j is row
if j<=7
temp1 = sum(cp_mesh(j:j+1,k:k+1,i));
temp2 = sum(temp1)/sum(sum(tributary(j:j+1,k:k+1)));
temp3 = min([temp3 temp2]);
clear temp1 temp2
else
break
end
end
else
break
end
end
cp_B1_2(i) = temp3;
clear temp3
end
cp_B1_2
Where,
cp_mesh = (81 x 126 x 49792) matrix
Accepted Answer
Jan
on 15 Jan 2023
Edited: Jan
on 15 Jan 2023
tributary = randn([81, 126]);
cp_mesh = randn([81, 126, 49792]);
tic
cp_B1_2 = zeros(49792, 1);
for i = 1:4979 % 49792
temp3 = Inf;
for k = 9:117
for j = 1:7
temp1 = sum(cp_mesh(j:j+1, k:k+1,i), 'all');
temp2 = temp1 / sum(tributary(j:j+1, k:k+1), 'all');
temp3 = min(temp3, temp2);
end
end
cp_B1_2(i) = temp3;
end
toc
This uses the shorter input, because the full set let exceed the runtime the allowed 55 seconds in the forum's online Matlab.
As dpb has mentioned already, cleaning the loops instead of breaking them earlier is more efficient and the clear commands waste time only.
You get save about 10%, if you calculate sum(tributary(j:j+1,k:k+1), 'all') before the loop and store it in a temporary array.
Now this is a fair point for a comparison with a vectorized approach:
tic;
out = Inf;
for k = 9:117
for j = 1:7
temp1 = sum(cp_mesh(j:j+1, k:k+1, 1:4979), [1, 2]);
temp2 = temp1 ./ sum(tributary(j:j+1, k:k+1), 'all');
out = min(out, temp2(:));
end
end
toc
For the full input data:
temp1 = sum(cp_mesh(j:j+1, k:k+1, :), [1, 2]);
0 Comments
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices 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!