我喜歡在這種情況下向後迭代,因爲這會在第一次執行循環時強制執行完整的內存分配。然後代碼會是這個樣子:
%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