How to create multiple data structures

16 views (last 30 days)
harshpurohit11
harshpurohit11 on 23 Jun 2018
Commented: Star Strider on 25 Jun 2018
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
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:

Star Strider
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
harshpurohit11
harshpurohit11 on 25 Jun 2018
Thanks a lot for the answer. Having tried this code, I am not able to work my way around the "Error using cell2struct - Invalid file name error" for the first entries in A. I tried converting array A to char but even that did not do any help.
Star Strider
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.

Sign in to comment.

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!