- The body of the parfor-loop must be independent. One loop iteration cannot depend on a previous iteration, because the iterations are executed in parallel in a nondeterministic order.
How to run two loops simulatenously which share varaibles in MATLAB?
1 view (last 30 days)
Show older comments
I am trying to implement some logic which can be simplified in the example below:
count = 5;
value = 0;
parfor i = 1:2
if i == 1
for u = 0:count
%Do dome work
pause(5);
value = value + 1;
end
else
while true
disp(value)
if(value > count)
break
end
end
end
end
end
I wanted to run two loops in parallel which share a certain variable(s). Above is the closest I could get. I realized if I used the parfor as shown, I can call each on its own worker. Unfortunately, I am getting the error The PARFOR loop cannot run due to the way variable 'value' has been used
Anyone with an idea how I can achieve the above successfully?
0 Comments
Answers (1)
Kunal Kandhari
on 18 Jan 2023
Hi,
Not all MATLAB for loops can be converted to parfor.
In your this part of code:
disp(value)
if(value > count)
break
end
there is an dependency of variable value on the following piece of code:
value = value + 1;
This stops you from being able to use a parfor.
To solve these problems, you must modify the code to use parfor. The body of the parfor-loop is executed in a parallel pool using multiple MATLAB workers in a nondeterministic order. Therefore, you have to meet following requirements for the body of the parfor-loop:
You can read more sbout the same using the following resources:
0 Comments
See Also
Categories
Find more on Parallel for-Loops (parfor) 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!