Search code examples
matlabstructevalcell

Avoiding eval in assigning data to struct array


I have a struct array called AnalysisResults, that may contain any MATLAB datatypes, including other struct arrays and cell arrays.

Then I have a string called IndexString, which is the index to a specific subfield of StructArray, and it may contain several indices to different struct arrays and cell arrays, for example: 'SubjectData(5).fmriSessions{2}.Stats' or 'SubjectData(14).TestResults.Test1.Factor{4}.Subfactor{3}'.

And then I have a variable called DataToBeEntered, which can be of any MATLAB datatype, usually some kind of struct array, cell array or matrix.

Using eval, it is easy to enter the data to the field or cell indexed by IndexString:

eval([ 'AnalysisResults.', IndexString, ' = DataToBeEntered;' ])

But is it possible to avoid using eval in this? setfield doesn't work for this.

Thank you :)


Solution

  • Well, eval surely is the easiest way, but also the dirtiest.

    The "right" way to do so, I guess, would be to use subsasgn. You will have to parse the partial MATLAB command (e.g. SubjectData(5).fmriSessions{2}.Stats) into the proper representation for those functions. Part of the work can be done by substruct, but that is the lightest part.

    So for example, SubjectData(5).fmriSessions{2}.Stats would need to be translated into

    indexes = {'.' , 'SubjectData',
               '()', {5},
               '.' , 'fmriSessions',
               '{}', {2},
               '.' , 'Stats'};
    indexStruct = substruct(indexes{:});
    AnalysisResult = subsasgn(AnalysisResult, indexStruct, DataToBeEntered);
    

    Where you have to develop the code such that the cell array indexes is made as above. It shouldn't be that hard, but it isn't trivial either. Last year I ported some eval-heavy code with similar purpose and it seemed easy, but it is quite hard to get everything exactly right.