Skip to Main Content Skip to Search
File Exchange
MATLAB Newsgroup
Link Exchange
  Blogs  
 Contest 
MathWorks.com

Loren on the Art of MATLAB

December 13th, 2005

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 .()

4 Responses to “Use Dynamic Field References”

  1. Ed Limbaugh replied on :

    I just stumbled across Loren’s blog quite by accident, and I really enjoy reading through the older postings. I think there is a solution to the second point in the Contraindications section of the article about dynamic field references: “If you don’t know the overall structure of your struct, … it’s hard to program generically with .()”

    Use ‘fieldnames’ to retrieve the names of all fields at one level of the structure. I’ve done something similar to the following a number of times:

    fn = fieldnames(mystruct);
    for lp=1:length(fn)
    doSomeOperation( mystruct.( fn{lp} ) );
    end

    I’ve become more comfortable just using the field names as the loop arguments outright.

    fn = fieldnames(mystruct);
    for lp=fn
    doSomeOperation( mystruct( lp{:} ) );
    end

    This works very well for homogenous structures or when your ‘doSomeOperation’ function knows how to handle different input types.
    For example, you might define doSomeOperation like this:

    function x = doSomeOperation(y)
    if ~isnumeric(y)
    x = [];
    else
    x = doSomethingForReal(y);
    end

    Anyway, it’s a thought.

  2. PIETRO replied on :

    I am writing Matlab code using this notation in order to manage fields in Matlab. I think it is a very good method. I am wondering if codes written using this notation could lead some problems when Matlab Compiler is applied, as it happens for the “eval” function.
    Eventually I ask you whether the use of “feval” can solve this problem or not.

    Thank you very much.

    Pietro Garofalo

  3. Loren replied on :

    Pietro-

    There are no issues with using dynamic field referencing and the compiler. I don’t see how using feval helps in any way. This method should be robust.

    –Loren

  4. Mag replied on :

    I happen to pass by your blog and saw your entries on MATLAB.
    I would like to ask you regarding structure used in MATLAB.
    But I am a beginner of MATLAB but I have to work on a project on B-splines.

    >>>> My problem is that I currently can only plot one spline on the axes. My data will always be over-written the moment I plot another axes. However, when I read from the MATLAB book. It seems that the example are assigning data to structure in a less interactive way with the user. Is there any ways that I can work on the data clicked by the user. Then retrieving the relevant data upon selecting on the spline drawn.

    Another problem of mine is that, after I have shifted the original spline to another location. After I apply ‘cla’ function, all the splines have been deleted. Is there any other functions that I can used to delete the original spline after shifting the spline to a new location without deleting other splines on the axes.

    Thanks a million,
    Magdalene

Leave a Reply


Loren Shure works on design of the MATLAB language at The MathWorks. She writes here about once a week on MATLAB programming and related topics.

  • Ulla Vainio: That error bar width adjustment was extremely useful and I would never have figured it out myself....
  • Peter Perkins: Jessee, there is a property that you can use to tag variables with units. For example, >> load...
  • Jessee: I could potentially see myself using dataset for casually looking at data, but from an application standpoint...
  • Loren: Oktay- It very much depends on the details of the calculations you are doing. Vectorization can sometimes...
  • Oktay: Hello, Is there any significant difference between using: - Vectorization inside a subfunction - Benefiting...
  • Loren: Clare- Yes, sum can sum a double vector: x = [.3 .4 pi/3] y = sum(x) x = 0.3 0.4 1.0472 y = 1.7472 You must...
  • Clare J: R2007a - Student Version When I use sum to sum a vector of type double I get this error message: ???...
  • Sarah Zaranek: Hi Jacob, Sorry about the slow response. You are correct that the code would be slower without the...
  • Navaneethan Santhanam: Thanks a lot, Loren! That worked perfectly.
  • Mike N: Should it be OK to use “persistent 221; variables in a deployed application? What if I have two...

These postings are the author's and don't necessarily represent the opinions of The MathWorks.

Related Topics