# How to linearize the nested parfor loop?

2 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!

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
Preetham Manjunatha on 18 Jul 2021
Thanks, it works! But there are way too many for loops, which I was trying to avoid.

R2021a

### Community Treasure Hunt

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

Start Hunting!