Setting up my structure with a cell array of char vectors.
3 ビュー (過去 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!