How to create multiple data structures
2 views (last 30 days)
Show older comments
I have two arrays A = {'a';'a';'a';'a';'b';'b';'c';'c';'c';'d';'d'} and B = [1,2,4,6,2,3,4,6,7,8,9]; length(A)=length(B). How can I create a data structure in work space such that a.values = [1,2,4,6], b.values = [2,3], c.values = [4,6,7] and d.values= [8,9]
Answers (2)
Stephen23
on 23 Jun 2018
Edited: Stephen23
on 23 Jun 2018
A much better idea would be to put them into one structure (or cell array):
[U,~,X] = unique(A);
C = accumarray(X(:),B(:),[],@(v){v});
S = struct('values',C)
Then you can simply get the values using basic MATLAB indexing:
S(1).values
S(2).values
... etc
and the corresponding name is given in U:
U{1}
U{2}
... etc
Using indexing is simpler and more reliable than dynamically accessing variable names. Dynamically accessing variable names is one way that beginners force themselves into writing slow, complex, buggy code that is hard to debug. Read this to know why:
0 Comments
Star Strider
on 23 Jun 2018
If you also want to use your ‘a’, ‘b’, ‘c’, ‘d’ field names in your structure, this works:
A = {'a';'a';'a';'a';'b';'b';'c';'c';'c';'d';'d'};
B = [1,2,4,6,2,3,4,6,7,8,9];
[Au,~,ic] = unique(A);
V = accumarray(ic, B(:), [], @(x){x});
S = cell2struct(V, Au, 1)
S =
struct with fields:
a: [4×1 double]
b: [2×1 double]
c: [3×1 double]
d: [2×1 double]
2 Comments
Star Strider
on 25 Jun 2018
My pleasure.
My code worked for me (in R2018a). I have no idea what the problem could be, since I do not know what data you are working with. My code does not create any file names.
See Also
Categories
Find more on Structures 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!