繁体   English   中英

Matlab-动态访问数据结构的一部分

[英]Matlab - access dynamically part of data structure

我有一个数据结构ABC ,我想访问其某些部分,以动态地从通过导入csv文件填充的单元格数组中读取对象名称。

For example, my data structure has following fields A.B.C
within B are B1, B2, B2, B3, B4, B5
within C are field_1, field_3, field_3
Names cell array with all the possibilities for B, imported from cvs

我想为每个B情况动态访问field_2 我从csv文件中导入了名称,并尝试传递如下名称:

A.(Names(1,1)).field_2

但出现错误

'Argument to dynamic structure reference must evaluate to a valid field name.'

当我打印数组的单个名称时,撇号就在那里。 例如Names(1,1)返回'B1'而不是B1

如何绕过撇号? 还是引用对象的更好方法?

我以emzet的评论为基础,并提供了一个可重现的示例,展示了它如何工作。 这是我的代码来重新创建您的结构:

A = struct();
A.B1 = struct();
A.B2 = struct();
A.B3 = struct();
A.B4 = struct();
A.B1.field_1 = 'testB1C1';
A.B1.field_2 = 'testB1C2';
A.B1.field_3 = 'testB1C3';
A.B1.field_4 = 'testB1C4';
A.B2.field_1 = 'testB2C1';
A.B2.field_2 = 'testB2C2';
A.B2.field_3 = 'testB2C3';
A.B2.field_4 = 'testB2C4';
A.B3.field_1 = 'testB3C1';
A.B3.field_2 = 'testB3C2';
A.B3.field_3 = 'testB3C3';
A.B3.field_4 = 'testB3C4';

NamesB = {'B1', 'B2', 'B3' ,'B4'};
NamesC = {'field_1', 'field_2', 'field_3' ,'field_4'};

现在,正如您所指出的,执行以下操作:

A.(NamesB(1)).(NamesC{1}) 

将返回错误:

Argument to dynamic structure reference must evaluate to a valid field name.

如果您这样做,则:

A.(NamesB{1}).(NamesC{1}) % notice the curly braces after NamesB.

ans =

'testB1C1'

将提供正确的价值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM