How to linearize the nested parfor loop?

10 views (last 30 days)
I have two variables i,j, where j index start depends on i index.
n = 3;
for i = 1:n
for j = i+1:n
% Feature matching
matches = getMatches(input, allDescriptors{i}, allDescriptors{j});
nf = size(matches, 2);
numMatches(i,j) = nf;
end
end
I am trying to linearize it using the below code:
n = 3;
M = n;
N = n;
parfor i = 1:M*N
% IND2SUB converts from a "linear" index into individual
% subscripts
[ii,jj] = ind2sub([M,N], i);
if (ii~=jj)
matches = getMatches(input, allDescriptors{ii}, allDescriptors{jj});
nf = size(matches, 2);
numMatches(i) = nf;
end
end
But have some entries on the lower part of the square matrix.
Any help is appreciated!

Accepted Answer

Jeff Miller
Jeff Miller on 18 Jul 2021
One approach is to set out all the desired pairs in advance. A crude way to do that is
pairs = zeros(0,2);
n = 3;
for i = 1:n % or reallyl just to n-1?
for j = i+1:n
pairs(end+1,:) = [i, j];
end
end
Then your parfor loop can just go through the preset pairs:
npairs = size(pairs,1);
parfor i = 1:npairs
ii = pairs(i,1);
jj = pairs(i,2);
matches = getMatches(input, allDescriptors{ii}, allDescriptors{jj});
nf = size(matches, 2);
numMatches(i) = nf;
end
  5 Comments
Jeff Miller
Jeff Miller on 18 Jul 2021
OK, then I guess you have to store the parfor results in a temporary vector and put them into numMatches after the parfor loop is done.
pairs = zeros(0,2);
n = 3;
for i = 1:n % or reallyl just to n-1?
for j = i+1:n
pairs(end+1,:) = [i, j];
end
end
npairs = size(pairs,1);
temp = zeros(npairs,1);
parfor i = 1:npairs
ii = pairs(i,1);
jj = pairs(i,2);
matches = getMatches(input, allDescriptors{ii}, allDescriptors{jj});
nf = size(matches, 2);
temp(i) = nf;
end
numMatches = zeros(n,n);
for i=1:npairs
ii = pairs(i,1);
jj = pairs(i,2);
numMatches(ii,jj) = temp(i);
end
Preetham Manjunatha
Preetham Manjunatha on 18 Jul 2021
Thanks, it works! But there are way too many for loops, which I was trying to avoid.

Sign in to comment.

More Answers (0)

Categories

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

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!