Doug's MATLAB Video Tutorials

February 27th, 2009

Dynamic field name usage

This short video shows how you can make your code shorter, more flexible, and readable by using a string variable to reference a field in a structure. This is called dynamic field name reference or “dot parens” notation. You can say: fName = ‘doug’ a.(fName) %this now refers to a.doug
In this particular example, a MATLAB user was writing out dozens of different cases, when one loop with dynamic field name reference makes the code so much easier.
I would also like to take this opportunity to welcome Dan Sutoyo, of Blink Dagger fame, to The MathWorks. Dan first came on to my radar when he started posting about MATLAB and commenting on this blog. Eventually we got talking about job opportunities at The MathWorks and I referred him for a position starting in the Engineering Development Group. Thanks for accepting the job and I hope to see you guest posting your tutorials here soon.

6 Responses to “Dynamic field name usage”

  1. Dan replied on :

    Thanks Doug, I am sure I will be learning greatly here and hope to deliver better tutorials in near future.

  2. Christos replied on :

    Thanks, another excellent post.

    And timely too. Actually I had a similar problem a few days ago and had addressed it with a switch/case statement.

    After your post though, I changed it and the code is now much better: more compact, less error-prone and easier to change (if needed).

    Too bad I hadn’t read it on time.

    Christos

  3. dhull replied on :

    Christos,

    Thanks for letting me know. I never know what videos really help people unless I read goodness like this in the comments.

    Thanks,
    Doug

  4. Prabhakar replied on :

    Vow!!!!!!! Goodbye eval..

    Thanks a lot!!
    Prabhakar

  5. dhull replied on :

    @Prabhakar,

    If I got one person to avoid unneeded EVALS, then this was all worth it! :)

    Doug

  6. Jeremy Gibson replied on :

    Doug – Thanks tons! I’ve been searching for a few days on code to dynamically reference field names that change by increments of 1 (i.e., data.signal_1, data.signal_2) and until now I was trying, unsuccessfully to index them via EVAL with a for loop. Your code is simpler and makes much more sense! Thanks Tons.

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


MathWorks

Doug Hull is a proud MathWorker who is on a mission to help you with MATLAB.

Doug's picture

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