MATLAB Answers

Getting Data from a struct-array with other structs in it, without a loop

23 views (last 30 days)
Hi Matlab Community,
I have got a problem getting data out of a struct-array (I think the structure is called struct-array) without using a for-loop.
I get data from simulations in the following structure:
Now I want to get a specific value (e.g. "PF") from all fields (1 to 12) in the struct PowerAnalysis.ECP.
The Power Analysis Struct has got this structure:
And the ECP Structure itself has got this structure:
I can access one result with the command:
K>> Post_Processing.RunData(1).PowerAnalysis.ECP.PF
ans =
0.6738 0.6738 0.6738
But if I try to access all the field by this command:
K>> Post_Processing.RunData(:).PowerAnalysis.ECP.PF
Expected one output from a curly brace or dot indexing expression, but there were 12 results.
I tried various things to get whole data. Of course I could use a loop, but I think that there is an easier and faster way than using a loop.
I have tried someting with structfun, but that yields to the same problem as mentioned befor:
test = @(s) Post_Processing.RunData(s).PowerAnalysis.ECP.PF
K>> test(1)
ans =
0.6738 0.6738 0.6738
test(:)
Input arguments to function include colon operator. To input the colon character, use ':' instead.
It would be very helpful if someone can help me with the problem, because it bothers me for two days now.
A second questions is: How is my data structure called ? I would say it's a structure-array with sub structures in it. But if I google this structure I do not get helping results on my topic, so I think the structure isn't described right by me.
Thanks in advance and kind greetings,
M.G.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 26 Feb 2021
Edited: Stephen Cobeldick on 26 Feb 2021
Using arrayfun to iterate over the elements of non-scalar structure Post_Processing.RunData:
fun = @(s) s.PowerAnalysis.ECP.PF; % all sub-structures must be scalar!
out = arrayfun(fun, Post_Processing.RunData, 'uni',0);
mat = vertcat(out{:}) % optional
Note that arrayfun just hides the loop inside, and is generally slower than using an explicit loop.
Or concatenate scalar sub-structures using comma-separated lists:
tmp = [Post_Processing.RunData];
tmp = [tmp.PowerAnalysis];
tmp = [tmp.ECP];
out = {tmp.PF}; % or:
mat = vertcat(tmp.PF);
Why syntaxes like Post_Processing.RunData(:).PowerAnalysis.ECP.PF will not work:

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by