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!