2

假设我struct在 Matlab 中有以下内容(从 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*

但不幸的是,它什么也没返回。有任何想法吗?

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

4

2 回答 2

3

您可以使用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);
于 2016-08-29T12:27:52.167 回答
2

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

提示:每次在变量或字段名称中看到数字时,请考虑是否不应该使用向量/数组/列表。

这适用于所有语言,但对于 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
于 2016-08-29T13:50:01.687 回答