Setting up my structure with a cell array of char vectors.
3 views (last 30 days)
Show older comments
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 Comments
Answers (1)
James Tursa
on 31 Oct 2016
Edited: James Tursa
on 31 Oct 2016
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 Comments
per isakson
on 1 Nov 2016
Edited: per isakson
on 1 Nov 2016
"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
See Also
Categories
Find more on Structures in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!