【问题标题】:Logical index of structure with various dimensioned fields具有各种维度字段的结构的逻辑索引
【发布时间】:2016-11-10 15:50:27
【问题描述】:

假设我有这样的结构:

S.index = 1:10;
S.testMatrix = zeros(3,3,10);
for x = 1:10
    S.testMatrix(:,:,x) = magic(3) + x;
end
S.other = reshape(0:39, 4, 10);

它包含一个 1x10 的向量、一个 3x3x10 的多页数组和一个 4x10 的矩阵。现在说我只想选择与 2 到 8 之间的索引对应的条目。mask = S.index > 2 & S.index < 8;

我首先尝试了structfun(@(x) x(mask), S, 'UniformOutput', 0);,它仅适用于矢量,这非常有意义。所以我想我需要做的就是扩大我的面具。所以我就这么做了。

test = structfun(@(x) x(repmat(mask, size(x, ndims(x) - 1), 1)), S, 'UniformOutput',0);

扩展的mask 对矩阵是正确的,但对于多页数组则不是。并且二维矩阵被展平为向量。

如果我要单独索引这些元素,我会这样做:

S2.index = S.index(mask);
S2.other = S.other(:,mask);
S2.testMatrix = S.testMatrix(:,:,mask);

我的用例是数百个结构,每个结构都有 20 多个字段。如何编写索引脚本?发生的确切问题仅限于具有 1xN 向量、3xN 和 4xN 矩阵以及 3x3xN 数组的结构。掩码是基于表示时间的向量之一构建的。每个结构的字段名称都是恒定的,因此我可以强制执行该操作并输入命令并将其作为函数运行,但我正在寻找一种智能方法来索引它。

更新:这看起来很有希望。

fn = fieldnames(S);
for x = 1:length(fn)
    extraDim = repmat({':'}, 1, ndims(S.(fn{x})) - 1);
    S2.(fn{x}) = S.(fn{x})(extraDim{:}, mask);
end

【问题讨论】:

    标签: matlab struct matrix-indexing


    【解决方案1】:

    您可以利用 the string ':' can be used as an index 而不是 : 的事实,并为该字符串构建一个 comma-separated list,为每个字段重复适当的次数:

    s = {':',':'}; % auxilary cell array to generate the comma-separated list
    S2 = structfun(@(f) f(s{1:ndims(f)-1}, mask), S, 'UniformOutput', false);
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    相关资源
    最近更新 更多