Setting up my structure with a cell array of char vectors.

6 次查看(过去 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!

回答(1 个)

James Tursa
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 个评论
Bryan Wilson
Bryan Wilson 2016-10-31
THANKS! What worked for me was...
struct1 = struct('a',char(zeros(10,1)),...
'c',zeros(10,1),'d',zeros(10,3),'e',zeros(10,3),...
'f',zeros(10,1),'g',zeros(10,1),'h',zeros(10,1));
bData = cellstr(['3';'4';'7']);
[struct1(:).b] = bData;
FYI, this puts field b at the bottom of the structure. You can reorder with some creativity.
per isakson
per isakson 2016-11-1
编辑:per isakson 2016-11-1
"when you don't want that 2nd behavior" &nbsp 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 CenterFile Exchange 中查找有关 Structures 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by