Concatenate same fields in multiple structures in a loop using field names
Show older comments
I have several .mat files and each is a structure with the same fields. For each field, I'd like to create an array that has the name of that field and is the concatenation of all structures with that field name. I can provide a psuedo-code, but not sure how to write it out for real:
firststruct has field names 'one' and 'two'
secondstruct has field names 'one' and 'two'
for i = 1:number of structure files I have (the .mat files)
get the field names
for j = 1:number of field names
'this would be the name of the first field (so 'one')' = this would create a vector that concatenates all .one fields;
'this would be the name of the second field (so 'two')' = this would create a vector that concatenates all .two fields;
end
end
To try to be clearer, if firststruct.one = [1,2] and secondstruct.one = [3,4], the result I'm hoping for is one = [1,2,3,4].
3 Comments
Stephen23
on 26 May 2020
"I'd like to create an array that has the name of that field ..."
Stephen23
on 26 May 2020
There are two possible situations:
1- you know all of the fieldnames in advance, in which case it is simple to explicitly allocate them to variables:
one = S.one;
two = S.two;
2- you don't know the fieldnames, in which case see previous comment. Note that having an unknown number of variables with unknown names in the workspace makes them difficult to process, increases the risk of bugs (e.g. overwriting a variable without any warning), and makes debugging difficult.
Personally I would just leave them in the structure: that little bit of extra typing makes the data easy to track and the code easy to maintain.
Accepted Answer
More Answers (0)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!