How can I record data from a parfor loop into an array?
10 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Dominik Rhiem
el 23 de Jun. de 2023
Comentada: Dominik Rhiem
el 26 de Jun. de 2023
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 comentarios
Matt J
el 23 de Jun. de 2023
Editada: Matt J
el 23 de Jun. de 2023
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]);
Respuesta aceptada
Matt J
el 23 de Jun. de 2023
Editada: Matt J
el 23 de Jun. de 2023
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]);
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!