Matlab dynamic field structure with cell arrays

How can I access the following structure path with dynamic field names:

var = 'refxtree.CaseDefinition.FlowSheetObjects.MaterialStreamObjects{8}.MaterialStreamObjectParams.Pressure.Value.Text'; fields = textscan(var,'%s','Delimiter','.'); 

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

In the end, I want to get and set field values.

+3
source share
3 answers

You need to create an appropriate input for subsref , possibly using substruct . Take a look at MATLAB help.

0
source

You can define an anonymous function to navigate this particular structure of the form top.field1.field2.field3{item}.field4.field5.field6.field7 (aside: is it really necessary to have such a complex 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 functions by calling

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

Note that fields requires seven elements. If you want to summarize the above, you will have to dynamically create the above functions.

0
source

In this case, it is easier to use EVAL:

 str = 'refxtree.CaseDefinition.FlowSheetObjects.MaterialStreamObjects{8}.MaterialStreamObjectParams.Pressure.Value.Text'; %# get x = eval(str) %# set evalc([str ' = 99']); 
0
source

Source: https://habr.com/ru/post/1482340/


All Articles