How to extract a specific data value from a field in a from multiple structures, and save into an array

1 view (last 30 days)
I have hundreds of structs named x01T0005, x01T0105, x01T0205 etc. Within each of these structs there is a field named U, from which I want to extract the value in the 81st row and 32nd column and save it into an array. I want to do this for the first 200 of my structs so that I end up with an array of 200 values containing the (81,32) value from each U field.
Thanks
  1 Comment
Stephen23
Stephen23 on 26 Jun 2018
Edited: Stephen23 on 26 Jun 2018
"I have hundreds of structs named x01T0005, x01T0105, x01T0205 etc"
How are these structures stored? I doubt that you sat and wrote out their names by hand, so presumably they are saved in files and imported into MATLAB somehow, in which case your task will be trivial once you import the structures into one array (e.g. a cell array). For example this is made easy by always using an output argument with load:
S = load(...)
If you do that in a loop then you can easily put the contents of the files into one array (the functions struct2cell or fieldnames may also be useful to you). Note that contrary to what some beginners think, it is much easier to process the contents of multiple .mat files when they contain variables with exactly the same names. Then you can trivially allocate them into one non-scalar structure.
In any case, avoid loading your data into lots of variables, for example "hundreds of structs named x01T0005, x01T0105, x01T0205 etc"- Dynamically accessing variable names is one way that beginners force themselves into writing slow, complex, buggy code that is hard to debug. Read this to know why:

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 26 Jun 2018
Edited: Stephen23 on 26 Jun 2018
Once you have your structures in a cell array C (easily achieved when importing), then this is trivial:
arr = nan(1,200);
for k = 1:200
arr(k) = C{k}.U(81,32);
end
You certainly avoid a lot of problems when you don't try to access variable names dynamically!

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Tags

Products


Release

R2016a

Community Treasure Hunt

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

Start Hunting!