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
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:
0 个评论
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 个评论
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 Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!