i有一个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')
访问它。
有什么方法可以将带有完整字段名称(带有点)的字符串传递给一个函数以检索此字段?还是有一种更好的方法来仅获取我在函数参数中选择的字段?
目标?当然,这将是一个字段名称的无用函数,但是我不会将字面名称的列表作为参数列表来准确接收这些字段。
您应该使用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命令。
一种方法是创建一个自我调用函数来执行此操作:
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