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.
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
About
Doug Hull is a proud MathWorker who is on a mission to help you with MATLAB.
Thanks Doug, I am sure I will be learning greatly here and hope to deliver better tutorials in near future.
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
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
Vow!!!!!!! Goodbye eval..
Thanks a lot!!
Prabhakar
@Prabhakar,
If I got one person to avoid unneeded EVALS, then this was all worth it! :)
Doug
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.