【问题标题】:How to do multilevel indexing on array of structs in Matlab?如何在 Matlab 中对结构数组进行多级索引?
【发布时间】:2014-08-22 17:31:59
【问题描述】:

假设我在 matlab 中使用以下方法创建了一个结构数组:

mystruct = repmat(struct('field1',1, 'field2', ones(10,1)), 10, 1 );

出于我的目的(除了简单的示例),我会发现使用以下方法获取矢量输出非常有用:

myvector = mystruct(:).field2(1) 

但是这给了我错误:

'Scalar index required for this type of multi-level indexing.'

编辑:我希望从数组中的每个结构中得到 one 向量的第一个元素,因此是一个 10x1 的“1”向量。

我可以轻松地手动使用 for 循环遍历我的结构中的每个值并分配给 myvector,但这看起来非常麻烦而且速度很慢。有什么想法吗?

【问题讨论】:

    标签: matlab data-structures indexing


    【解决方案1】:

    我假设您正在尝试将所有 field2 向量收集到 myvector

    myvector = [mystruct(:).field2];
    

    返回:

    myvector =
    
         1     1     1     1     1     1     1     1     1     1
         1     1     1     1     1     1     1     1     1     1
         1     1     1     1     1     1     1     1     1     1
         1     1     1     1     1     1     1     1     1     1
         1     1     1     1     1     1     1     1     1     1
         1     1     1     1     1     1     1     1     1     1
         1     1     1     1     1     1     1     1     1     1
         1     1     1     1     1     1     1     1     1     1
         1     1     1     1     1     1     1     1     1     1
         1     1     1     1     1     1     1     1     1     1
    

    编辑:根据您的评论,您可以使用上述内容并丢弃您不想要的数据(在这种情况下为myvector(2:end,:) = [];)。不过,这是一种非常占用内存的方法。可能有一种方法可以使用structfun 或类似方法来提取您想要的东西,但我需要考虑如何去做。

    EDIT2:试试arrayfun(@(x) x.field2(1), mystruct),看看它是否会返回您要查找的内容。

    【讨论】:

    • +1 感谢您的回答,我应该指定我想要的:我基本上想要结构数组中每个结构中 field2 的所有第一个元素。我会修改我的问题,但我认为你已经明白了。
    • 根据您的评论更新,稍后我会再看一遍,尝试提出更好的答案。
    【解决方案2】:

    您可以分两步:

    1. 将你的 struct filed2 作为一个矩阵:

      foo = [mystruct.field2];

    2. 获取第一行(包含 field2 的第一个索引)

      myvector = foo(1, :);

    【讨论】:

    • 谢谢,就是这样,所以我认为没有单个命令,我总是需要将它分成两个步骤?
    猜你喜欢
    • 2012-04-03
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 2021-06-10
    • 1970-01-01
    相关资源
    最近更新 更多