How to linearize the nested parfor loop?

6 次查看(过去 30 天)
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
Jeff Miller 2021-7-18
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 个评论
Jeff Miller
Jeff Miller 2021-7-18
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
Thanks, it works! But there are way too many for loops, which I was trying to avoid.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by