【问题标题】:Dynamical access to nested fields in Matlab在 Matlab 中动态访问嵌套字段
【发布时间】:2013-05-23 08:54:23
【问题描述】:

(如何)我可以在 Matlab 中动态访问嵌套字段吗?我正在考虑这样一个测试用例:

a = struct;
a.foo.bar = [];

place = {'foo', 'bar'};

a.(place{:})

% instead of the following, which only works if know in advance
% how many elements 'place' has
a.(place{1}).(place{2})

【问题讨论】:

标签: matlab struct


【解决方案1】:

我不太满意的一个解决方案是:

getfield(a, place{:})

【讨论】:

  • +1:当你不知道嵌套层次的时候,恐怕是唯一的选择了。
  • 如果您检查getfield 的来源,它基本上是一个循环迭代为a = a.(place{i})。我也没有看到其他方式
【解决方案2】:

只是为了变化,你可以使用subsref()

a.foo.bar = 'hi';
place     = {'foo', 'bar'};

% Build subs for referencing a structure and apply subsref
typesub   = [repmat({'.'},1,numel(place)); place];

subsref(a,substruct(typesub{:}))
ans =
hi

毫无疑问,如果您必须构建typesubgetfield() 的可读性和速度会更快(否则对于这样的基本任务,速度比较是难以辨别的)。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-29
  • 1970-01-01
  • 2011-07-23
  • 2011-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多