Concatenate fields of a structure into a matrix
Show older comments
I have a structure that has 10 fields. I want to take the fields and put them into a single matrix. So, I have struct:
Struct =
struct with fields:
Trt_1: {8×2×2 cell}
Trt_2: {16×2×2 cell}
Trt_3: {10×2×2 cell}
Trt_4: {12×2×2 cell}
Trt_5: ''
Trt_6: ''
Trt_7: ''
Trt_8: ''
Trt_9: ''
Trt_10: ''
I want to take Trt_1, Trt_2, Trt_3, Trt_4 out of the structure and concatenate them into a single matrix that would have a row count of 46 (8+16+10+12=46) and the dimension 46x2x2
Thank you everyone - wrote a crazy code that looped over a bunch of if statements to extract the data but it's too complicated and doesn't work under certain conditions. Quick note, this is a script I'm using to analyze different data sets with different numbers of treatments. I'd like a code that can handle processing a data set of Trt_1, Trt_2, Trt_5 with no Trt_3 and no Trt_4, and also handle a different amount of treatments and rows of data. So, nothing hard coded.
3 Comments
Jacqueline Kelly
on 25 Sep 2020
madhan ravi
on 25 Sep 2020
Edited: madhan ravi
on 25 Sep 2020
It’s simply:
Copy = cat(1, S{ : }) % don’t have to define one after the another
First of why do copy paste? Haven’t you heard of writetable() , write2cell() and co?
Jacqueline Kelly
on 25 Sep 2020
Answers (1)
Peter O
on 25 Sep 2020
Long-term, it sounds like you might want to consider a different data structure, if that's an option.
In the interim, try cell2mat?
F = fieldnames(orderfields(S)); % Return an alphanumerically sorted listing
A = []
for ix=1:numel(F)
if ~isempty(S.(F{ix}))
A = cat(1,A,cell2mat(S.(F{ix})));
end
end
2 Comments
Quick caveat -- the above solution assumes you have numeric data in those internal fields. If they are cells and you know they will all be of size Nx2x2 (i.e. the solution you're seeking):
F = fieldnames(orderfields(S)); % Return an alphanumerically sorted listing
A = cell(0,2,2);
for ix=1:numel(F)
if ~isempty(S.(F{ix}))
C = S.(F{ix});
A = cat(1,A,C{:});
end
end
Jacqueline Kelly
on 25 Sep 2020
Categories
Find more on Whos 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!