Parallel computing of "for" loop

14 views (last 30 days)
Hi, I am solving a program in which I use a for loop for the computation of some entities. One of the entity is being updated in each loop. I am not able to use parfor loop which gives the reason that it cannot be used in case of updating entities. Is their any other way to implement parallel computing and speed up the process?
Thanks for your response in advance.

Accepted Answer

Steven Lord
Steven Lord on 29 Mar 2024
Is it the case that the computation of the value for the entity in the second iteration of your loop requires the value of the entity computed during the first iteration of your loop? Something like this basic scenario?
n = 5;
x = ones(1, n);
for k = 2:n
x(k) = (x(k-1).^2)+1
end
x = 1×5
1 2 1 1 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
x = 1×5
1 2 5 1 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
x = 1×5
1 2 5 26 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
x = 1×5
1 2 5 26 677
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
If so you can't use parfor because your loop iterations are not independent. You must compute the value of x(4) before it is possible for you to compute the value of x(5) in the example above, for instance.
Now the question of whether or not it's possible to speed up your code is a different matter entirely. We can't offer any firm guidance on that because you haven't shown us your code, but you can use the tools for measuring and profiling your code listed on this documentation page along with Code Analyzer to try to identify bottlenecks and/or suggested improvements in your code.
  3 Comments
Edric Ellis
Edric Ellis on 24 Apr 2024 at 13:52
It might still be worth sketching out your use-case. There are types of computation that can be run in parfor that appear to be dependent on previous values. These are known as "reduction" operations, like this:
maxValue = -Inf;
parfor i = 1:100
maxValue = max(maxValue, rand());
end
disp(maxValue)
0.9999
Muhammad Hassaan Bin Tariq
Muhammad Hassaan Bin Tariq on 24 Apr 2024 at 14:52
I have something like this:
M = zeros(rows,2);
maxValue = 10000;
parfor i = 1:100
reduction = 1;
maxValue = maxValue - reduction;
M(i,1) = i;
M(i,2) = maxValue;
end
plot(M(:,1),M(:,2))

Sign in to comment.

More Answers (0)

Categories

Find more on Parallel for-Loops (parfor) in Help Center and File Exchange

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!