Concatenate fields of a structure into a matrix

13 次查看(过去 30 天)
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 个评论
madhan ravi
madhan ravi 2020-9-25
编辑:madhan ravi 2020-9-25
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
Jacqueline Kelly 2020-9-25
Because I need to analyze the data in another program. I'm just using Matlab to organize it as its a large data set (1000s) that I can't manually organize by treatment or ID

请先登录,再进行评论。

回答(1 个)

Peter O
Peter O 2020-9-25
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 个评论
Peter O
Peter O 2020-9-25
编辑:Peter O 2020-9-25
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
Jacqueline Kelly 2020-9-25
Awesome - I figured it out a different way...
S = struct2cell(Struct);
Copy=cat(1,S{1},S{2},S{3},S{4},S{5},S{6},S{7},S{8},S{9},S{10});
CopySampleIDS=Copy(:,1)
for t=1:length(Targets)
CopyData(:,t)=Copy(:,2,t);
end
I have my sample IDS which are strings and my data which are doubles (numbers). CopySampleIDS returns the list of sample IDS in their individualized cells, conserving the order, so that my CopyData gives me back the number data corresponding to each sample ID.
Thank you for your assistance-

请先登录,再进行评论。

标签

Community Treasure Hunt

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

Start Hunting!

Translated by