在结构体元胞数组的字段中查找值

Find a value in a field of a cell array of structures

已定义 GNU/Octave 元胞数组

dict = 
{
  [1,1] =
    scalar structure containing the fields:
      id = integers
      vl = ... -2, -1, 0, 1, 2, ...
  [1,2] =
    scalar structure containing the fields:
      id = positive integers
      vl = 1, 2, 3, 4, ...
  [1,3] =
    scalar structure containing the fields:
      id = negative integers
      vl = -1, -2, -3, -4, ...
}

如何查找(在 Octave 代码中,无需循环!)在字段中具有给定值的结构,例如,在 id 字段中包含 'integer' 的结构,或 -1vl 字段中。

更新:该命令将像 find(dict,'vl','-1') 一样运行,返回 1, 31 0 1

搜索功能的可能实现方式如下:

function arrayvalues = findinfield(mycellarray, inputfield, outputfield, fieldvalue)

  positions = ~cellfun(@isempty, regexp({[mycellarray{:}].(inputfield)}, fieldvalue));
  arrayvalues = {[mycellarray{positions}].(outputfield)};

end

对于精确匹配,将 ^$ 分别添加到正则表达式的开头和结尾。

用例:

findinfield(dict, "id", "vl", "integers")
ans = 
{
  [1,1] = ... -2, -1, 0, 1, 2, ...}
  [1,2] = 1, 2, 3, 4, ...}
  [1,3] = -1, -2, -3, -4, ...}
}

findinfield(dict, "id", "vl", "^integers$")
ans = 
{
  [1,1] = 1, 2, 3, 4, ...}
}

findinfield(dict, "id", "vl", "negative")
ans = 
{
  [1,1] = -1, -2, -3, -4, ...}
}