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

3 visualizaciones (últimos 30 días)
Bryan Wilson
Bryan Wilson el 31 de Oct. de 2016
Editada: per isakson el 1 de Nov. de 2016
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!

Respuestas (1)

James Tursa
James Tursa el 31 de Oct. de 2016
Editada: James Tursa el 31 de Oct. de 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 comentarios
Bryan Wilson
Bryan Wilson el 31 de Oct. de 2016
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 el 1 de Nov. de 2016
Editada: per isakson el 1 de Nov. de 2016
"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

Iniciar sesión para comentar.

Categorías

Más información sobre Structures en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by