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

10 visualizaciones (últimos 30 días)
Dominik Rhiem
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
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 comentarios
Matt J
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]);
Dominik Rhiem
Dominik Rhiem el 26 de Jun. de 2023
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.

Iniciar sesión para comentar.

Respuesta aceptada

Matt J
Matt J el 23 de Jun. de 2023
Editada: Matt J el 23 de Jun. de 2023
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]);

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by