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

使用函数/字符串访问复杂的matlab结构,matlab,Matlab,我有一个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')来访问它 是否有任何方法可以将带有完整字段名(带点)的字符串传递给函数以检索此字段?还是有

我有一个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')
来访问它

是否有任何方法可以将带有完整字段名(带点)的字符串传递给函数以检索此字段?还是有更好的方法只获取通过函数参数选择的字段


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

一种方法是创建一个自调用函数来执行此操作:

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

您应该使用
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'));
test函数首先使用
作为分隔符拆分输入,并创建一个单元格数组
F
,其中每个其他元素都填充
,然后将其元素作为参数传递给
子结构

请注意,如果涉及到
结构的数组,它将得到第一个。对于
a.b(i).c(j).d
passing
b.c.d
将返回
a.b(1).c(1).d
。请参阅以了解应如何处理它


作为补充说明,我将您的输入变量
struct
重命名为
strct
,因为
struct
是一个内置的MATLAB命令。

很抱歉缺席这么久,这个解决方案对我来说非常有效,非常感谢!谢谢,它确实有效,但另一个解决方案对我来说更清楚。