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

13 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

  5. Paul replied on :

    I’m using some super dumb techniques to process multiple variables with a differing prefix..

    var_str = {’gamrf’,'pt’,’s’};
    for var = 1:length(var_str)
    string = strcat(var_str{var},’mean_max = squeeze(max(shiftdim(’,var_str{var},’mean,2)));’); cmd = char(string); eval(cmd);
    string = strcat(var_str{var},’mean_min = squeeze(min(shiftdim(’,var_str{var},’mean,2)));’); cmd = char(string); eval(cmd);
    end

    This is really hitting things with a hammer.. Can someone direct me to an enlightening way of digging myself out of hammerland?

  6. Loren replied on :

    Paul-

    Follow the ideas in this blog article instead! Do NOT name your variables specially. Instead use some base name for a structure and have the fields be the various names you want to refer to. That is one of the main points of the article.

    –Loren

  7. Shalin Mehta replied on :

    Hi Loren,

    I stumbled upon this page while searching a solution to following problem. I searched usergroups to no avail.

    I need to retrieve value of a field from the structure and name of the field is based on user input. Following is the sample code:

    test.fourarray=zeros(3,3,3,3);
    fname=’fourarray’;

    eval([’test.’ ‘fourarray’]);
    ERROR: ??? Index exceeds matrix dimensions.

    I just can’t figure out what’s happening!
    Why do I get above error (which occurs btw irrespective of the size and type of the field)?

  8. Loren replied on :

    Shalin-

    Something else must be going on (or there’s a bug in the version you are running). I just tried your code in R2008b and it works fine.

    However, you don’t need the eval statement. Try this instead:

    test.(fname)
    

    and add whatever trailing indexing you want.

    –Loren

  9. Shalin Mehta replied on :

    Yes something else was wrong (may be spurious variables in workspace). It worked alright after clearing unused workspace variables.

    Thanks…

  10. Frank Kohler replied on :

    Hi Loren,

    regarding number 6. I have a similar problem.

    I have perform an simulation with Simulink and have stored some variables with Simulink ToWorkspace blocks at my workspace. Due to this I have now variables with a special name at my workspace e.g.

    a = 3;
    b = 4;
    c = 5;

    Now I want to save the simulation results at a data structure (e.g. D). At a cell array (e.g. simResults), I have stored all names of the variables which will be stored by the ToWorkspace blocks at the workspace:

    simResults = {’a';’b';’c'};

    When I try to save the simulation results at my data structure D, I can’t solve it without eval(). Can you please help me, to do it without?

    D = struct();

    for i = 1:length(simResults)
    % Desired, something without eval()
    % D.(simResults{i}) = .(simResults{i});
    % Possible, at the moment only with eval()
    D.(simResults{i}) = eval(simResults{i});
    end

    -Frank

  11. Loren replied on :

    Frank-

    You can’t do that without eval. There is not way to reference a variable without naming it unless you somehow create an appropriate string to evaluate.

    You are better off creating the structure and using that to start with, if that’s an option. Or use a cell array, one cell per variable, similarly.

    –Loren

  12. Alex replied on :

    Hi Loren,

    Are dynamic fields the same thing people call in Perl or Python hatches (previously known as associative arrays)? I am in the bioinformatic area and most scientists use Python or Perl and usually pick on me ’cause Matlab doesn’t have hatches. I found dynamic fields some time ago but still have doubts whether they are the same thing.

    Thanks,
    A

  13. Loren replied on :

    Alex-

    Sort of but not really (and I think you mean hash perhaps, not hatch?)… structs are more like structures in C. the containers.Map class is more like associative arrays in perl or python. The notation .() simply allows variable “indexing” into a struct with a variable fieldname rather than just a fixed literal string.

    –Loren

Leave a Reply

Wrap code fragments inside <pre> tags, like this:

<pre class="code">
a = magic(3);
sum(a)
</pre>

If you have a "<" character in your code, either follow it with a space or replace it with "&lt;" (including the semicolon).


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.

  • Jun: I totally can not believe it, Loren. You are really helpful. Thank you so much, MATLAB master!
  • Loren: Wow folks- Always lots of interest when there’s a quickie to try out! I will only make 2 general...
  • Loren: Jun- ismember is your friend here: >> [aa,ind] = ismember(Array2,Arra y1) aa = 1 1 1 1 1 1 1 ind = 1 2 1 4 4 3...
  • Dan: I like the first way better than the second way. Combining the arrays into one and running any is nice, although...
  • James Myatt: How about I = (a == 0 | b == 0); a(I) = []; b(I) = [];
  • Tunc: Hello Loren, love your blog because of such inspiring and challenging comments to such ’small’...
  • Pekka Kumpulainen: Here is my tradeoff. I usually want to keep the original variables as they are most probably...
  • Iain: Followup: Of course, to allow NaNs (counting them as non-zero): mask = (a~=0) & (b~=0); The mask says “a...
  • Matt Fig: I would usually go with something like this: y = a&b; x = a(y); y = b(y); But I was surprised to find...
  • kk: c=all([a;b]) a(c) a(b)

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