开发者

Matlab dynamic fieldnames structure with cell arrays

How can i access the following structure path with dynamic fieldnames:

var = 'refxtree.CaseDefinition.FlowSheetObjects.MaterialStreamObjects{8}.MaterialStreamObjectPara开发者_开发百科ms.Pressure.Value.Text';

fields = textscan(var,'%s','Delimiter','.');

refxtree.(fields{:}) does not work because MaterialStreamObjects contains a cell array of which I want to access the 8th cell and then continue down the structure path.

In the end I want to get and set the fieldvalues.


You need to build the appropriate input to subsref, possibly using substruct. Look at the MATLAB help.


You can define an anonymous function to navigate this particular kind of structure of the form top.field1.field2.field3{item}.field4.field5.field6.field7 (as an aside: is it really necessary to have such a complicated structure?).

getField = @(top,fields,item)top.(fields{1}).(fields{2}).(fields{3}){item}.(fields{4}).(fields{5}).(fields{6}).(fields{7})

setField = @(top,fields,item,val)subsasgn(top.(fields{1}).(fields{2}).(fields{3}){item}.(fields{4}).(fields{5}).(fields{6}),struct('type','.','subs',fields{7}),val);

You use the functions by calling

fieldValue = getField(refxtree,fields,8);
setField(refxtree,fields,8,newFieldValue);

Note that fields is required to have seven elements. If you want to generalize the above, you will have to dynamically create the above functions


In this case, it is easier to just use EVAL:

str = 'refxtree.CaseDefinition.FlowSheetObjects.MaterialStreamObjects{8}.MaterialStreamObjectParams.Pressure.Value.Text';

%# get
x = eval(str)

%# set
evalc([str ' = 99']);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜