我喜欢在这种情况下向后迭代,因为这会在第一次执行循环时强制执行完整的内存分配。然后代码会是这个样子:
%Reset the structure
s = struct;
for ix = 97:-1:1
%Do stuff
%Store the data
s(ix).frame = ix;
s(ix).str = strength;
s(ix).freq = frequency;
end
如果一个框架依赖于下一个,或者你不知道一共有多少帧都会有,你可以向前扫描。 97帧不是很多数据,所以你可能不需要过多地关心优化问题的预分配部分。
%Reset the structure
s = struct;
for ix = 1:97
%Do stuff
%Store the data
s(ix).frame = ix;
s(ix).str = strength;
s(ix).freq = frequency;
end
或者,如果你真的需要结构的预分配阵列的性能,但你不知道它会在一开始有多大,你可以做这样的事情:
%Reset the structure
s = struct;
for ix = 1:97
%Do stuff
%Extend if needed
if length(s)<ix
s(ix*2).frame = nan; %Double allocation every time you reach the end.
end
%Store the data
s(ix).frame = ix;
s(ix).str = strength;
s(ix).freq = frequency;
end
%Clip extra allocation
s = s(1:ix);
哦,非常感谢。你的额外信息对我来说也很有用。谢谢 – saya 2012-03-07 20:13:35