Parfor and symmetric matrix

Hi,
I need to fill in a matrix. Since it is symmetrical, the two for loops look like this
for i = 1 : m
for j = i : n
operation on the matrix ....
end
end
The other elements of the matrix are filled in by using "permute" (it is a 3D matrix).
I am now modifying the code to make it parallelizable. I tried with the parfor like this
parfor i = 1 : m
for j = i : n
operation on the matrix ....
end
end
At running time, I get the error because matlab does not know the value of "i". I guess this is because the two "for" are not independent.
My question is:
  • is there a way to fill in a symmetric matrix by exploiting the symmetry, and using the parfor? Or shall I ignore the symmetry, have the second "for" starting from 1, and getting rid of "permute" ?

Answers (1)

Matt J
Matt J on 12 Aug 2021
Edited: Matt J on 12 Aug 2021
[I,J]=ndgrid(1:m,1:n);
keep=J>=I;
I=I(keep);
J=J(keep);
parfor k=1:numel(I)
i=I(k);
j=J(k);
operation on the matrix ....
end

4 Comments

Maria
Maria on 13 Aug 2021
Edited: Maria on 13 Aug 2021
This is a very elegant way I would have never thought about... Thanks!
mmm...I just tried the code with a generic matrix, and the parfor still does not work, see code below:
m = 3;
n = 3;
[I,J]=ndgrid(1:m,1:n);
keep=J>=I;
I=I(keep);
J=J(keep);
H = rand(2,2);
parfor k=1:numel(I)
i=I(k);
j=J(k);
H(i,j) = 3;
end
Matt J
Matt J on 13 Aug 2021
Edited: Matt J on 13 Aug 2021
Here's one possible fix.
temp = zeros(m,n);
H=0;
parfor k=1:numel(I)
dH=temp;
i=I(k);
j=J(k);
dH(i,j) = 3;
H=H+dH;
end
Matt J
Matt J on 13 Aug 2021
Edited: Matt J on 13 Aug 2021
Another possible fix (probably better):
temp = zeros(size(I));
H=0;
parfor k=1:numel(I)
temp(k)=3;
end
idx=sub2ind([m,n],I,J);
H(idx)=temp(:);

Sign in to comment.

Categories

Find more on MATLAB Parallel Server in Help Center and File Exchange

Products

Release

R2021a

Tags

Asked:

on 12 Aug 2021

Edited:

on 13 Aug 2021

Community Treasure Hunt

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

Start Hunting!