필터 지우기
필터 지우기

How can I record data from a parfor loop into an array?

조회 수: 9 (최근 30일)
Dominik Rhiem
Dominik Rhiem 2023년 6월 23일
댓글: Dominik Rhiem 2023년 6월 26일
I have a parfor loop in which I perform some calculations which I would ideally like to store in an array. Some code:
array = zeros(4,5,3);
parfor j = 1:3
for jj = 1:4
value = rand;
idx = randi(5)
array(jj,idx,j) = value;
end
end
Error: Unable to classify the variable 'array' in the body of the parfor-loop. For more information, see Parallel for Loops in MATLAB, "Solve Variable Classification Issues in parfor-Loops".
There is another index selection within the nested loop, which I here represent with the random index selection between 1 and 5. Why is this not possible and what can I do instead?
  댓글 수: 2
Matt J
Matt J 2023년 6월 23일
편집: Matt J 2023년 6월 23일
I know you've simplified your example for the purposes of discussion, but I hope it's clear that you would never use parfor or any other kind of loop for a task like this. Instead, you would do,
[m,n,p]=deal(4,5,3);
[I,~,K]=ndgrid(1:m,1,1:p);
J=randi(n,size(K));
value=rand(size(K));
array=accumarray([I(:),J(:),K(:)], value(:), [m,n,p]);
Dominik Rhiem
Dominik Rhiem 2023년 6월 26일
For such a task, yes, of course. As you said, I did this specifically as a simplification, the inner loop is an iterative process, and the outer loop provides different input parameters for the inner process. I don't see how that could be vectorised. I just make use of these two indices which are necessary anyway for saving the output of the inner loop. The inner random index is also, in reality, not random, of course.

댓글을 달려면 로그인하십시오.

채택된 답변

Matt J
Matt J 2023년 6월 23일
편집: Matt J 2023년 6월 23일
Why is this not possible
From the documentation for sliced variables (which array is supposed to be in this case):
Form of Indexing. Within the first-level of indexing for a sliced variable, exactly one indexing expression is of the form i, i+k, i-k, or k+i. The index i is the loop variable and k is a scalar integer constant or a simple (non-indexed) broadcast variable. Every other indexing expression is a positive integer constant, a simple (non-indexed) broadcast variable, a nested for-loop index variable, colon, or end.
what can I do instead
array = zeros(5,12);
parfor k = 1:size(array,2)
value = rand;
idx = randi(5);
tmp=array(:,k);
tmp(idx)=value;
array(:,k)=tmp;
end
array=permute( reshape(array,5,4,3) ,[2,1,3]);

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by