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.

채택된 답변

Walter Roberson
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
Nathaniel Werner
Nathaniel Werner 2018년 6월 10일
Hello, Thank you for responding and sorry for not replying sooner.
I have some questions for clarification.
  1. When you say de-vectorize in and make it a 2D array again, the variable is already a 2D array. Can you explain what you mean?
  2. The reason I am using in(k) not in(i,:) is because k will count from 1:1:N*M. I don't want to replace the row numbers, I just want to save them, but I'm not too picky as to how that is done. If the way you described will accomplish the job then I can do that. And I don't think I need logicals, simply doubles representing the integer row numbers should be fine. I plan on just removing all rows that are zero once the for loop is finished. Unfortunately, I am limited by the tools in R2016a.
in(in==0)=[]
Walter Roberson
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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품


릴리스

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by