2012-03-07 119 views
0

我有97倍,其迭代一個循環,並有兩個arrrays將數據放置在matlab結構中?

  1. 頻率[1024]
  2. 強度[1024]

這些陣列循環的每次迭代之後改變值。因此其價值的變化之前,我需要把它們放在一個structure.For實例的結構將類似於

s(1).frame=1  %this will show the iteration no. 
s(1).str=strength 
s(1).freq=frequency 

現在我需要97層這樣的結構說S(1)到S(97)在數組中。

我的問題是:如何在循環中創建一個結構數組。請幫幫我。

回答

2

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

%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); 
+0

哦,非常感謝。你的額外信息對我來說也很有用。謝謝 – saya 2012-03-07 20:13:35