beginh
beginh

Reputation: 1153

how to preallocate a structure in matlab

I do have a simple question, but it doesn't go for me. I want to preallocate a structure that contains many fields. I want to obtain it like this: structure S 1x30 and each of 30 fields should be a structure 1x50 (some of 50 entries integers, some cells with strings, some subarrays). Is this possible to preallocate it without giving the exact names for each of 50 fields?

cheers!

Upvotes: 1

Views: 3504

Answers (1)

slayton
slayton

Reputation: 20319

AFAIK struct fields must be named, however, those names don't need to be hard coded.

For example if I have a struct foo that has a field named bar I can access that field like so:

name = 'bar';
data = foo.(name);  % the same as data = getfield(data, name);

The foo.(name) notation indicates that one can make field names from variables (dynamic field names) for which the doc can be found here. Additionally you can use this to create fields.

name = 'bar'
for i = 1:10
  nameI = [bar, num2str(i)] ;
  foo.( nameI) = []; % the same as foo = setfield(foo, nameI, []);
end

The struct foo now has 10 fields named bar1, bar2, ... bar10.

If you absolutely don't want names and simply want indicies then what you probably want is a cell array. Cell arrays are like regular matlab vectors except that they can contain anything.

c = {'1234', 1234, [1 2 3 4],  [1 2; 3 4], @disp, {1 ,2, 3}};

For example c is a cell array that contains a string, scalar, vector, matrix and then function handle, and another cell array.

You can access the contents of an individual cell using the curly braces {}. So c{1} would return '1234' whereas c{2} would return a number.

You could use either of these methods to pre-allocate a data structure that fits what you've described.

Upvotes: 2

Related Questions