Search code examples
matlabstructeval

Matlab: writting dicom metadata with dynamic fieldnames


I'm trying to write dicom metainformations to a dicom file. Here the fieldnames are changing dynamicaly depending on the given metainformations.

for j = 1:obj.pln.propStf.numOfBeams
    eval(['meta.FractionGroupSequence.Item_1.ReferencedBeamSequence.Item_' num2str(j) '.ReferencedBeamNumber = j;'])
    eval(['meta.FractionGroupSequence.Item_1.ReferencedBeamSequence.Item_' num2str(j) '.BeamDoseSpecificationPoint = [j,j,j];'])
    eval(['meta.FractionGroupSequence.Item_1.ReferencedBeamSequence.Item_' num2str(j) '.BeamDose = j;'])
    eval(['meta.FractionGroupSequence.Item_1.ReferencedBeamSequence.Item_' num2str(j) '.BeamMeterset = j;'])
    eval(['meta.FractionGroupSequence.Item_1.ReferencedBeamSequence.Item_' num2str(j) '.BeamDosePointDepth = j;'])
    eval(['meta.FractionGroupSequence.Item_1.ReferencedBeamSequence.Item_' num2str(j) '.BeamDosePointSSD = j;'])
end

As you can see here meta.FractionGroupSequence.Item_1.ReferencedBeamSequence.Item_' num2str(j) '.ReferencedBeamNumber = j; the fieldnames of the struct changes dynamicaly with the amount of beams given in obj.pln.propStf.numOfBeams.

The Problem with this approach is, that if I'm going to try to have something like that: eval(['meta.FractionGroupSequence.Item_1.ReferencedBeamSequence.Item_' num2str(j) '.ReferencedBeamNumber = 'TEST';']). The eval function tries to find the text 'TEST'.

So the question is, is there a different approach for the given problem instead of using eval?


Solution

  • Instead of using eval MATLAB allows you to access dynamic struct fields with strings:

    mystruct.hello=1;
    mystruct.('hello')=1; % equivalent.
    

    just do:

    meta.FractionGroupSequence.Item_1.ReferencedBeamSequence.(['Item_'num2str(j)']).ReferencedBeamNumber = j;