将数据放在matlab中的结构中?

Posted

技术标签:

【中文标题】将数据放在matlab中的结构中?【英文标题】:placing data in structures in matlab? 【发布时间】:2012-03-07 19:47:23 【问题描述】:

我有一个循环 97 次,并且有两个数组

    频率[1024] 实力[1024]

这些数组在每次循环迭代后改变值。所以在它的值改变之前,我需要把它们放在一个结构中。例如,结构就像

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

现在我需要 97 个这样的结构,比如数组中的 s(1) 到 s(97)。

我的问题是:如何在循环中创建结构数组。请帮帮我。

【问题讨论】:

【参考方案1】:

在这种情况下,我喜欢向后迭代,因为这会在第一次执行循环时强制分配完整的内存。然后代码看起来像这样:

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

【讨论】:

哦,非常感谢。你的额外信息对我也很有用。谢谢

以上是关于将数据放在matlab中的结构中?的主要内容,如果未能解决你的问题,请参考以下文章

MATLAB如何提取结构体中数据

matlab 怎么将374个结构体数据保存在一个数组中?用哪个函数

MatLab数据结构

如何将txt中的数据整理到Matlab中画图

matlab中如何看函数结构体中的数据

Matlab导入txt格式数据某几行如何进行