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