How to create multiple data structures

2 次查看(过去 30 天)
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]

回答(2 个)

Stephen23
Stephen23 2018-6-23
编辑:Stephen23 2018-6-23
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 2018-6-23
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 个评论
harshpurohit11
harshpurohit11 2018-6-25
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 2018-6-25
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by