adding all fields of a structures
조회 수: 12 (최근 30일)
이전 댓글 표시
I have a following structure with fields:
say, my_struct = struct with fields:
bin_1: [851×19 table]
bin_2: [868×19 table]
bin_3: [164×19 table]
bin_4: [104×19 table]
bin_5: [348×19 table]
bin_6: [406×19 table]
bin_7: [303×19 table]
bin_8: [323×19 table]
bin_9: [275×19 table]
bin_10: [110×19 table]
I want to have a structure with one field that is all field combined together. Something like my_new_struct= bin_1: [3500(approx.)×19 table]
i.e. my_new_struct= sum of all tables of my_struct
Could someone help me with the program for that?
댓글 수: 1
Stephen23
2023년 11월 1일
This is fragile data design: as Voss correctly pointed out, the order of fields may not be the order you expect or require. The cause is because you have hidden meta-data (i.e. pseudo indices) in the fieldnames. Much better data design would use actual indices (rather then pseudo-indices) e.g. in a simple structure array or a cell array. That also significantly simplifies the code required to merge all of the tables:
vertcat(C{:}) % from a cell array
vertcat(S.F) % from a structure array
Better data design leads to much better code.
답변 (3개)
Voss
2023년 11월 1일
Here's one way to do that:
% a structure like your "my_struct", but with only 3 fields:
my_struct = struct( ...
'bin_1',array2table(repmat("bin_1_data",2,2)), ...
'bin_2',array2table(repmat("bin_2_data",4,2)), ...
'bin_3',array2table(repmat("bin_3_data",3,2)))
% combine all the tables:
C = structfun(@(x){x},my_struct);
T = vertcat(C{:})
However, that may not combine the tables in the order you wanted. In order to impose an order, you can do something like this:
% get the names of the fields:
fn = fieldnames(my_struct);
% reorder them somehow:
% fn = sort(fn); % sorted lexicographically
% fn = natsort(fn) % sorted by the number they contain
fn = fn(end:-1:1); % reverse
% combine all the tables in that order:
C = cellfun(@(f)my_struct.(f),fn,'UniformOutput',false);
T = vertcat(C{:})
See natsort in the File Exchange, which may give you the ordering you're after in this case.
댓글 수: 0
Bruno Luong
2023년 11월 1일
편집: Bruno Luong
2023년 11월 1일
s.bin_1=array2table(rand(2,3));
s.bin_2=array2table(rand(3,3));
s.bin_3=array2table(rand(4,3));
c=struct2cell(s);
newstruct.T = cat(1,c{:});
disp(newstruct.T)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!