如何查询匹配特定模式的 Matlab 结构中的变量列表?

How to query list of variables in Matlab struct matching a certain pattern?

假设我在 Matlab 中有以下 struct(从 JSON 文件读取):

>>fs.
fs.dichte              fs.hoehe               fs.ts2                 
fs.temperatur          fs.ts3                 fs.viskositaet
fs.ts1                 fs.ts4

fs.ts* 个组件中的每个组件都包含另一个 struct。在这种特殊情况下,ts 的索引从 1 变为 4,但在另一种情况下,它也可能是 2 或 7。你明白了吧?我希望程序足够灵活以处理任何可能的输入。 所以我的问题归结为:如何查询ts的最大索引? 在理想情况下,这会起作用:

who fs.ts*

但不幸的是,它只是 returns 什么都没有。有什么想法吗?

顺便说一句,我正在使用 Octave,没有可用于测试的 Matlab;但是,确实应该有一个在两种环境下都适用的解决方案。

可以使用fieldnames获取结构体的所有字段名,然后使用regexp提取以ts开头的字段名并提取数字。然后您可以比较数字以找到最大的数字。

fields = fieldnames(fs);

number = str2double(regexp(fields, '(?<=^ts)\d+$', 'once', 'match'));
numbers = number(~isnan(number));

[~, ind] = max(number);
max_field = fields{ind};
max_value = fs.(max_field);

不是您确切问题的答案,但听起来像 tsN 字段,您应该有一个带有列表的 ts 字段。

提示:每当您在变量或字段名称中看到数字时,想想您是否不应该使用 vector/array/list。

所有语言都是如此,但 Octave 更是如此,因为一切都是数组。即使您有三个字段名为 ts1ts2ts3 的标量值,您真正拥有的是三个字段,其值是一个大小为 1x1 的数组。

在 Octave 中你可以有两件事。或者 ts 的值是一个元胞数组,元胞数组的每个元素都是一个标量结构;或者是一个结构数组。当每个结构具有不同的键时使用结构元胞数组,当所有结构具有相同的键时使用结构数组。

结构数组

octave> fs.ts = struct ("foo", {1, 2, 3, 4}, "bar", {"a", "b", "c", "d"});
octave> fs.ts # all keys/fields in the ts struct array
ans =

  1x4 struct array containing the fields:

    foo
    bar

octave> fs.ts.foo # all foo values in the ts struct array
ans =  1
ans =  2
ans =  3
ans =  4

octave> numel (fs.ts) # number of structs in the ts struct array
ans =  4

octave> fs.ts(1) # struct 1 in the ts struct array
ans =

  scalar structure containing the fields:

    foo =  1
    bar = a

octave> fs.ts(1).foo # foo value of the struct 1
ans =  1

标量结构元胞数组

但是,我不确定 JSON 是否支持结构数组之类的东西,您可能需要一个结构列表。在这种情况下,您最终会得到一个结构标量元胞数组。

octave> fs.ts = {struct("foo", 1, "bar", "a"), struct("foo", 2, "bar", "b"), struct("foo", 3, "bar", "c"), struct("foo", 4, "bar", "d"),};
octave> fs.ts # note, you actually have multiple structs
ans = 
{
  [1,1] =

    scalar structure containing the fields:

      foo =  1
      bar = a

  [1,2] =

    scalar structure containing the fields:

      foo =  2
      bar = b

  [1,3] =

    scalar structure containing the fields:

      foo =  3
      bar = c

  [1,4] =

    scalar structure containing the fields:

      foo =  4
      bar = d

}
octave-gui:28> fs.ts{1} # get struct 1
ans =

  scalar structure containing the fields:

    foo =  1
    bar = a

octave-gui:29> fs.ts{1}.foo # value foo from struct 1
ans =  1