adding all fields of a structures
12 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commento
Stephen23
il 1 Nov 2023
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.
Risposte (3)
Matt J
il 1 Nov 2023
Modificato: Matt J
il 1 Nov 2023
Tables=arrayfun(@(f)mystruct.(f) ,"bin_"+(1:10) ,'uni',0);
my_new_struct.Bin=vertcat(Tables{:});
Voss
il 1 Nov 2023
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 Commenti
Bruno Luong
il 1 Nov 2023
Modificato: Bruno Luong
il 1 Nov 2023
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 Commenti
Vedere anche
Categorie
Scopri di più su Structures in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!