Setting up my structure with a cell array of char vectors.
조회 수: 4 (최근 30일)
이전 댓글 표시
I need a structure to contain a cell array of character vectors (cell array of strings). The structure looks OK if I just set up a character array, but when I change it to an cell array of strings, my structure dimensions change. The culprit is field 'b'. In the example below, struct1 has the correct dimensions (1x1), but 'b' is just a char array. When I change 'b' to a cell array of strings, as in struct2, the structure dimensions change (3x3).
struct1 = struct('a',char(zeros(10,1)),'b',['3';'4';'7'],...
'c',zeros(10,1),'d',zeros(10,3),'e',zeros(10,3),...
'f',zeros(10,1),'g',zeros(10,1),'h',zeros(10,1));
struct2 = struct('a',char(zeros(10,1)),'b',cellstr(['3';'4';'7']),...
'c',zeros(10,1),'d',zeros(10,3),'e',zeros(10,3),...
'f',zeros(10,1),'g',zeros(10,1),'h',zeros(10,1));
What am I missing? Please help!
댓글 수: 0
답변 (1개)
James Tursa
2016년 10월 31일
편집: James Tursa
2016년 10월 31일
You are missing a special "feature" of the struct function when one of the inputs is a cell array:
https://www.mathworks.com/help/matlab/ref/struct.html?searchHighlight=struct
From this link:
If value is not a cell array, then s is a scalar structure, where s.(field) = value.
If value is a cell array, then s is a structure array with the same dimensions as value. Each element of s contains the corresponding element of value. For example, s = struct('f',{'a','b'}) returns s(1).f = 'a' and s(2).f = 'b'.
This can be irritating at times when you don't want that 2nd behavior. So you will be forced to re-code things to build the struct a bit piecemeal if you want that cell array to be part of the struct in the same manner as the char array.
댓글 수: 3
per isakson
2016년 11월 1일
편집: per isakson
2016년 11월 1일
"when you don't want that 2nd behavior"   add an extra pair of braces
sa1 = struct( 'f1', {num2cell(1:6)} );
sa2 = struct( 'f1', num2cell(1:6) );
whos sa*
outputs
Name Size Bytes Class Attributes
sa1 1x1 896 struct
sa2 1x6 784 struct
or I didn't read carefully enough
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!