How to linearize the nested parfor loop?

3 vues (au cours des 30 derniers jours)
Preetham Manjunatha
Preetham Manjunatha le 17 Juil 2021
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!

Réponse acceptée

Jeff Miller
Jeff Miller le 18 Juil 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 commentaires
Jeff Miller
Jeff Miller le 18 Juil 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 le 18 Juil 2021
Thanks, it works! But there are way too many for loops, which I was trying to avoid.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Parallel for-Loops (parfor) dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by