使用函数/字符串访问复杂的Matlab结构体

4

我有一个 Matlab 结构体,其中包含多个级别(例如 a.b(j).c(i).d)。我想编写一个函数以提取所需的字段。如果该结构体只有一级,那么这将很容易:

function x = test(struct, label1)
  x = struct.(label1)
end

例如,如果我有结构体a.b,我可以通过test('b')来获取b。但是,如果我有一个结构体a.b.c,我不能使用test('b.c')来访问它的子字段。

有没有办法将带有点的完整字段名作为字符串传递给函数以检索此字段?或者是否有更好的方法通过函数参数仅获取我选择的字段?

目标?当然,对于一个字段名来说,这将是一个无用的函数,但我想传递一个字段名列表作为参数,以准确地接收这些字段。

2个回答

2
您应该使用subsref函数:
function x = test(strct, label1)
F=regexp(label1, '\.', 'split');
F(2:2:2*end)=F;
F(1:2:end)={'.'};
x=subsref(strct, substruct(F{:}));
end

要访问a.b.c,您可以使用以下方法:

subsref(a, substruct('.', 'b', '.', 'c'));

测试函数首先使用.作为分隔符拆分输入,并创建一个单元数组F,其中每个其他元素都填充了.,然后将其元素作为参数传递给substruct

请注意,如果涉及到structs的数组,则会获取第一个。对于a.b(i).c(j).d,传递b.c.d将返回a.b(1).c(1).d。有关应处理方式的信息,请参见此问题

另外,我将您的输入变量struct重命名为strct,因为struct是MATLAB的内置命令。


很抱歉长时间未能回复,这个解决方案对我非常有效,非常感谢! - lakerz

1
一种方法是创建一个自调用函数来实现这个功能:
a.b.c.d.e.f.g = 'abc'
value = getSubField ( a, 'b.c.d.e.f.g' )

  'abc'

function output = getSubField ( myStruct, fpath )
  % convert the provided path to a cell
  if ~iscell(fpath); fpath = strread ( fpath, '%s', 'delimiter', '.' ); end
  % extract the field (should really check if it exists)
  output = myStruct.(fpath{1});
  % remove the one we just found
  fpath(1) = [];
  % if fpath still has items in it -> self call to get the value
  if isstruct ( output ) && ~isempty(fpath)
    % Pass in the sub field and the remaining fpath
    output = getSubField ( output, fpath );
  end
end

谢谢,这个确实有效,但是另一个解决方案对我来说更清晰明了。 - lakerz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接