Loop through structure elements with parfor

1 visualización (últimos 30 días)
Matthew Thompson
Matthew Thompson el 18 de Mzo. de 2019
Comentada: Matthew Thompson el 20 de Mzo. de 2019
I have a structure with programatically generated fieldnames (let's call it myStruct), and an optimization program (let's call it optfunc) needs to run on data contained in each fieldname. I would like to use parfor to accelerate the process, but the normal way to loop through structs creates unclassified variables. Any tips on how this can be fixed? E.g.:
myFields = fieldnames(myStruct);
nFields = size(myFields,1);
parfor iField = 1:nFields
dataSet = myStruct.(myFields{iField});
optOut = optfunc( dataSet );
end

Respuesta aceptada

Edric Ellis
Edric Ellis el 19 de Mzo. de 2019
Given the following example data
myStruct = struct('one', rand(1), ...
'two', rand(2), ...
'three', rand(3));
My slight adaption of your program works correctly:
myFields = fieldnames(myStruct);
nFields = size(myFields,1);
out = NaN(1, nFields);
parfor iField = 1:nFields
dataSet = myStruct.(myFields{iField});
out(iField) = max(dataSet(:));
end
But note that myStruct is not sliced in this case - as @Walter suggests, you could use struct2cell to achieve that.
myContents = struct2cell(myStruct);
out2 = NaN(1, numel(myContents));
parfor iField = 1:numel(myContents)
dataSet = myContents{iField};
out2(iField) = max(dataSet(:));
end
  1 comentario
Matthew Thompson
Matthew Thompson el 20 de Mzo. de 2019
Yes, the struct2cell command was just what I was overlooking. Thank you both.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Structures 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