Loren on the Art of MATLAB

Turn ideas into MATLAB

Note

Loren on the Art of MATLAB has been archived and will not be updated.

Use Dynamic Field References

Use dynamic field references, the notation .(), where possible, instead of setfield, getfield, and eval.

History

In MATLAB 6.5 (Release 13), we introduced dynamic field references into MATLAB. What are they and why should you use them?

In MATLAB, there are 3 basic types of arrays, traditional ones where you index using parentheses (), cell arrays where you can address the contents using curly braces {}, and structures (known in MATLAB as the type struct) where you access elements using the dot . notation.

Before R13, if you had collected information into a variable, call it ind, about which parts of an array you wanted to either index into or to change, you could do so using the variable in a straight-forward manner - if your array was a regular or cell array. By that, I mean that you could do things like:

y = x(ind)
x(ind) = 17
       
% With cells, you typically access the contents
% of one cell at a time.
c{ind(1)} = x(ind(1))

However, there was no symmetry with how to accomplish the same task if your array was a struct and you had the fieldnames in a variable; instead you had to use setfield and getfield. There was extra overhead for accessing structure elements compared to other array types. And that's why dynamic field indexing was introduced.

Example

Preferred:

fldnm = 'fred';
s.(fldnm) = 18;
y = s.(fldnm)

Not Recommended:

s  =  setfield(s,'fldnm',18);
y = getfield(s,'fldnm');

eval(['s.' fldnm ' = 18']);
eval(['y = s.',fldnm])

Benefits

  • Speed - when you can use .(), it is much faster. Part of the reason is because you don't have the overhead of calling yet another function, i.e., setfield or getfield. An additional reason is that MATLAB can work on the structure field in place and unnecessary copies are not made. Contrast these two cases, using setfield and using dynamic field referencing:
    s = setfield(s,fldnm,3);
    s.(fldnm) = 3;
    

    The first line requires at least 2 copies of the structure s while the second line requires space for only one instance.

  • Readability -- code is easier to understand since you can see the components of the structure.
  • Analyzability - programs that use eval can be particularly hard to analyze, for example for dependency reports.

Contraindications

  • There are certain very complex calling sequences for setfield that can't be translated into .() notation easily.
  • If you don't know the overall "structure" of your struct (e.g., all names at one "level"), it's hard to program generically with .()

  • print

Comments

To leave a comment, please click here to sign in to your MathWorks Account or create a new one.