gpt4 book ai didi

matlab - 具有各种维度字段的结构的逻辑索引

转载 作者:太空宇宙 更新时间:2023-11-03 20:23:37 26 4
gpt4 key购买 nike

假设我有这样的结构:

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

最佳答案

您可以利用 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);

关于matlab - 具有各种维度字段的结构的逻辑索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40531672/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com