Preallocate structure of cells in matlab

只愿长相守 提交于 2019-12-11 01:46:40

问题


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.


回答1:


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".




回答2:


One more possibility (that I find easier to read) is to init each field separately.

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


来源:https://stackoverflow.com/questions/14376903/preallocate-structure-of-cells-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!