How to use a matrix in parfor?
Show older comments
Hello,
I have troubles with using parfor. I have program similar to this (heat transfer):
A=rand(20,20,2);
d=rand(20);
parfor i=2:19
for j=2:19
A(i,j,2)=d(i)*A(i+1,j,1)+d(i+1)*A(i-1,j,1)+d(i-1)*A(i,j+1,1)+A(i,j-1,1);
end
end
There is always error like: The PARFOR loop cannot run due to the way variable 'A' is used .
tank you very much Lukas
3 Comments
Juraj Hliník
on 18 Sep 2018
From Troubleshoot Variables in parfor-Loops Documentation
If you run into variable classification problems, consider these approaches before you resort to the more difficult method of converting the body of a parfor-loop into a function.
If you use a nested for-loop to index into a sliced array, you cannot use that array elsewhere in the parfor-loop.
The code on the top does not work because A is sliced and indexed inside the nested for-loop.
The code on the bottom works because v is assigned to A outside the nested loop. You can compute an entire row, and then perform a single assignment into the sliced output.
Invalid
A = zeros(4, 10);
parfor i = 1:4
for j = 1:10
A(i, j) = i + j;
end
disp(A(i, 1))
end
Valid
A = zeros(4, 10);
parfor i = 1:4
v = zeros(1, 10);
for j = 1:10
v(j) = i + j;
end
disp(v(1))
A(i, :) = v;
end
ahmad eldeeb
on 6 Nov 2021
What if I want to calculate A_new=A_old+v?
I'm skeptical that parfor is going to make things faster here. Try the following simpler test. The times shown are what I get with a 12 worker default local profile.
N=2000;
A=rand(N,N);
d=rand(N,1);
B=A(:,:,1);
C=B;
tic
for j=2:N-1
for i=2:N-1
C(i,j)=d(i)*B(i,j-1);
end
end
toc %Elapsed time is 0.014457 seconds.
tic
parfor j=2:N-1
for i=2:1999
C(i,j)=d(i)*B(i,j-1);
end
end
toc %Elapsed time is 1.889115 seconds.
Answers (1)
Namnendra
on 19 Jun 2022
0 votes
The different iterations in a parfor loop work independently. So, if "i" is the iterating variable in a parfor loop, you can't use A[i]=A[i+1], because the order of different iterations of loop can vary. You can call a function instead to perform the necessary operation.
1 Comment
Rik
on 15 Nov 2022
Could you give example?
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!