Search code examples
stringmatlabcell

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


I am getting this error "Argument to dynamic structure reference must evaluate to a valid field name." I have a struct called spectData and it looks like this

spectData{1} = 

data: [256x26 double]
textdata: {1x26 cell}
colheaders: {1x26 cell}
Row: [256x1 double]
Col: [256x1 double]
Cho: [256x1 double]
Cho0x25SD: [256x1 double]
Cho0x2FCit: [256x1 double]
PCho: [256x1 double]
PCho0x25SD: [256x1 double]

I try and assign this in a function call the line of code looks like this. This is the line of code that matlab says the error is at.

 SDdata = spectData{sliceNum - firstSlice}.(MetabMapSDString);

where metabString is a string of one of the names for example 'PCho0x25SD' spectData has 4 sub structs in total all like this one I displayed. What am I doing wrong?? It is a double so it should be ok I thought.


Solution

  • Matlab can give this sometimes misleading error message when you accidentally pass a cell array instead of a string. The following example gives the same error:

    fields = {'foo', 'bar'}
    s = struct('foo', 23, 'bar', pi)
    
    for f = fields
      disp(f)
      s.(f) = 0
    end
    

    If this is your problem (test the actual type of your field name with e.g. whos), it should help to say f = char(f).