필터 지우기
필터 지우기

How to create multiple data structures

조회 수: 5 (최근 30일)
harshpurohit11
harshpurohit11 2018년 6월 23일
댓글: Star Strider 2018년 6월 25일
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