matlab 数组构造,如何在MATLAB中初始化结构数组?

到目前为止,使用repmat是预分配结构的最有效方法:

N = 10000;

b = repmat(struct('x',1), N, 1 );

使用Matlab 2011a,这比通过索引进行预分配要快10倍,例如

N = 10000;

b(N).x = 1

索引方法仅比不预先分配略快。

No preallocation: 0.075524

Preallocate Using indexing: 0.063774

Preallocate with repmat: 0.005234

下面的代码,以备您验证。

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

>>

附言 如果有人可以解释,我很想知道为什么会这样。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值