How to linearize the nested parfor loop?

6 visualizaciones (últimos 30 días)
Preetham Manjunatha
Preetham Manjunatha el 17 de Jul. de 2021
Comentada: Preetham Manjunatha el 18 de Jul. de 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!

Respuesta aceptada

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

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by