如何在MATLAB中初始化结构数组? [英] How to initialize an array of structs in MATLAB?
本文介绍了如何在MATLAB中初始化结构数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在MATLAB中预分配结构数组?我想在此示例中预分配"a",以使其不会多次调整大小.
How can I preallocate an array of structs in MATLAB? I want to preallocate "a" in this example so that it does not resize several times.
a = []
for i = 1:100
a(i).x = i;
end
推荐答案
使用repmat
是迄今为止最有效的预分配结构的方法:
Using repmat
is by far the most efficient way to preallocate structs :
N = 10000;
b = repmat(struct('x',1), N, 1 );
与使用索引进行预分配相比,使用Matlab 2011a的速度要快〜10倍,如
This is ~10x faster using Matlab 2011a than preallocating via indexing, as in
N = 10000;
b(N).x = 1
索引方法仅比不预先分配要快.
The indexing method is only marginally faster than not preallocating.
No preallocation: 0.075524
Preallocate Using indexing: 0.063774
Preallocate with repmat: 0.005234
下面的代码,以备您验证.
Code below in case you want to verify.
clear;
N = 10000;
%1) GROWING A STRUCT
tic;
for ii=1:N
a(ii).x(1)=1;
end
noPreAll = toc;
%2)PREALLOCATING A STRUCT
tic;
b = repmat( struct( 'x', 1 ), N, 1 );
for ii=1:N
b(ii).x(1)=1;
end;
repmatBased=toc;
%3)Index to preallocate
tic;
c(N).x = 1;
for ii=1:N
c(ii).x(1)=1;
end;
preIndex=toc;
disp(['No preallocation: ' num2str(noPreAll)])
disp(['Preallocate Indexing: ' num2str(preIndex)])
disp(['Preallocate with repmat: ' num2str(repmatBased)])
命令窗口中的结果:
No preallocation: 0.075524
Preallocate Indexing: 0.063774
Preallocate with repmat: 0.0052338
>>
PS .我想知道为什么这是真的,如果有人能解释的话.
P.S. I'd be interested to know why this is true, if anyone can explain it.
这篇关于如何在MATLAB中初始化结构数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文