How to correct the error “Valid indices for 'variable' are restricted in PARFOR loops”
1 次查看(过去 30 天)
显示 更早的评论
I am trying to set up a parfor nested loop in MatLab R2016a as below.
N = size(A,1);
M = size(v,1);
in = zeros(N*M,1);
parfor i=1:N
for j=1:M
k = (i-1)*M-j;
if sqrt(sum((A(i,:)-v(j,:)).^2))<=tol
in(k) = i;
end
end
end
However, I am getting the following error Valid indices for 'in' are restricted in PARFOR loops. Is there some way I can correct this because both arrays A and v are considerably large, over 40,000 rows for A. Thanks very much.
0 个评论
采纳的回答
Walter Roberson
2018-6-9
Step 1: go back and de-vectorize your in, making it a 2D array again.
Step 2: use temporary variables to process one row at a time, and afterwards
in(i, :) = temporary
It looks to me as if for each row, the columns that are within the tolerance distance should be replaced with the row number, and the ones not within tolerance should stay 0. If you had a logical vector for the row, that would be equivalent to multiplying the vector by the row number.
To get the logical vector you could use pdist2(), or you could perform the equivalent code using bsxfun or the new implicit expansion facilities of R2016b or later.
2 个评论
Walter Roberson
2018-6-13
You have
in = zeros(N*M,1);
that is a vector. Instead use
in = zeros(M, N);
Normally I would have said zeros(N, M) given your N*M, but later in the code when you calculated k, you were doing so consistent with zeros(M,N)
"k will count from 1:1:N*M."
Don't do that for parallel work.
in = zeros(N, M);
parfor i=1:N
Ai = A(i,:);
ini = zeros(1,M);
for j=1:M
if sqrt(sum((Ai-v(j,:)).^2))<=tol
ini(j) = i;
end
in(i, ;) = ini;
end
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!