Search code examples
matlabmatlab-struct

How do I access structure fields dynamically?


I have a structure with many fields which are vectors of different lengths. I would like to access the fields within a loop, in order. I tried getfield as follows but MATLAB doesn't like that. How can I do this?

S = struct('A', [1 2], 'B',[3 4 5]);
SNames = fieldnames(S);
for loopIndex = 1:2
  field = getfield(S, SNames(loopIndex));
  %do stuff w/ field
end
??? Index exceeds matrix dimensions

I'm using structures in the first place because an array would have trouble with the different field lengths. Is there a better alternative to that?


Solution

  • Try dynamic field reference where you put a string in the parenthesis as seen on the line defining stuff.

    S = struct('A', [1 2], 'B',[3 4 5]); 
    SNames = fieldnames(S); 
    for loopIndex = 1:numel(SNames) 
        stuff = S.(SNames{loopIndex})
    end 
    

    I concur with Steve and Adam. Use cells. This syntax is right for people in other situations though!