2012-03-07 114 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