How can I record data from a parfor loop into an array?
조회 수: 10 (최근 30일)
이전 댓글 표시
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
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
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]);
채택된 답변
Matt J
2023년 6월 23일
편집: Matt J
2023년 6월 23일
Why is this not possible
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 Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!