在Matlab中预分配单元格结构 [英] Preallocate structure of cells in matlab
问题描述
我使用一种名为test
的结构,并带有以下布局"(whos test, test
的结果)
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
导致
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
发出命令test5.timestamp=tempstamp;test5.timeseries=tempseries;whos test5,test5
时得到一个
Name Size Bytes Class Attributes
test5 1x1 8449048 struct
test5 =
timestamp: {[0] [0] [0]}
timeseries: {[44000x8 double] [44000x8 double] [44000x8 double]}
因此在test
中再现布局".这很奇怪,不是吗?
进一步使用test2.timestamp{2}=now
不能与test3
和test4
一起使用.
好的,这在文档help struct
中进行了说明,但是如何在一行中预分配1x1 struct
之类的1x1 struct
之类的1x1 struct
?最好没有这些temp*
变量.
Thus reproducing the "layout" in test
. This is strange, isn't it?
Further using test2.timestamp{2}=now
is not working as with test3
and 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.
推荐答案
使用带有单元格的struct
来初始化带有单元格的字段需要深度为2的单元格:
Using struct
with cells to init a field with cell requires depth-2 cell:
test=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)} });
有关参考,请参见 struct
doc有关字段包含单元格数组".
For reference see struct
doc the example regarding "Fields that Contain Cell Arrays".
这篇关于在Matlab中预分配单元格结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!