Search code examples
matlabstructurecell

Preallocate structure of cells in matlab


I use a structure called test with the following "layout" (result of whos test, test)

  Name      Size              Bytes  Class     Attributes
  test      1x1             8449048  struct              
test = 
     timestamp: {[7.3525e+05]  [7.3525e+05]  [7.3525e+05]}
    timeseries: {[44000x8 double]  [44000x8 double]  [44000x8 double]}

For speed issues, I want to preallocate that with zeros. I found some ways, which result in other "layouts":

test2=struct('timestamp',cell(1,3),'timeseries',cell(1,3));
test3=struct('timestamp',{0,0,0},'timeseries',{zeros(44000,8),zeros(44000,8),zeros(44000,8)});
tempstamp={0,0,0};
tempseries={zeros(44000,8),zeros(44000,8),zeros(44000,8)};
test4=struct('timestamp',tempstamp,'timeseries',tempseries);
whos test2 test3 test4,test2,test3,test4

resulting in

  Name       Size              Bytes  Class     Attributes
  test2      1x3                 176  struct              
  test3      1x3             8448824  struct              
  test4      1x3             8448824  struct              
test2 = 
1x3 struct array with fields:
    timestamp
    timeseries
test3 = 
1x3 struct array with fields:
    timestamp
    timeseries
test4 = 
1x3 struct array with fields:
    timestamp
    timeseries

When issuing the commands test5.timestamp=tempstamp;test5.timeseries=tempseries;whos test5,test5 one gets

 Name       Size              Bytes  Class     Attributes
  test5      1x1             8449048  struct              
test5 = 
     timestamp: {[0]  [0]  [0]}
    timeseries: {[44000x8 double]  [44000x8 double]  [44000x8 double]}

Thus reproducing the "layout" in test. This is strange, isn't it?
Further using test2.timestamp{2}=now is not working as with test3and test4.
Okay, this is described in the documentation help struct, but how can I preallocate such 1x1 struct like test or test5 within one line? Best without those temp* variables.


Solution

  • Using struct with cells to init a field with cell requires depth-2 cell:

    test=struct('timestamp',{cell(1,3)},'timeseries',{cell(1,3)});
    

    or

    test3 = struct( 'timestamp', { {0,0,0}},...
                    'timeseries',{ {zeros(44000,8),zeros(44000,8),zeros(44000,8)} });
    

    For reference see struct doc the example regarding "Fields that Contain Cell Arrays".