Stuart’s MATLAB Videos

Watch and Learn

Dynamic field name usage 15

Posted by Doug Hull,

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.

15 CommentsOldest to Newest

Christos replied on : 2 of 15
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
dhull replied on : 3 of 15
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
Jeremy Gibson replied on : 6 of 15
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.
devaraj munian replied on : 7 of 15
Thanks Doug for a wonderful post. How can we store the string as a list. for i=1:n filenames=['simulation' num2str(i)] end I want to store the filenames as a list such that filenames(1)=simulation1 filenames(2)=simulation2 filenames(3)=simulation3 Then i want to use the filesnames(n) individually to create xls file like simulation1.xls,simulation2.xls,simulatio3.xls,etc. Help is really appreciated.
Doug replied on : 8 of 15
for i = 1:n filename{i} = ['simulation' num2str(i) '.xls']; end Note this is a CELL array. It acts slightly differently, but is the right thing. Note the curly braces {}.
Markus replied on : 9 of 15
Hi Doug, thanks a lot for all the great tutorials on Matlab. I really learned a lot from you. ;-) But know I am stucked with a simple problem for hours. I want to save an list of arguments to a variable in the beginning of my m-file so that I can configure the plotting options for all plots at once. I tried the following to define the options list: LegendText={'Location','SouthEast', 'Interpreter', 'latex','FontSize',16}; PlotOptions={'MarkerSize',5,'LineWidth',1,'DisplayName',FileName{i}} But this does not work when calling the functions for i = 1:10 plot (x,y{i},PlotOptions); legend1 = legend('show','-DynamicLegend'); legend ([legend1, LegendText]) end Do you have any idea how to use "dynamic field names" in the argument list with a variable which is later running in a loop (in this case the variable FileName{i})?? Thanks a lot in advance for any tip! Markus
Markus replied on : 11 of 15
Hi Doug, thanks a lot for your fast answer: here is my full code (I just exchanged long data stuff to the variables x and y) FileName{1}='TestA_try1.txt' FileName{2}='TestA_try2.txt' FileName{3}='TestB_try1.txt' x=1:1:20; y{1}=2.*x+x y{2}=3.*x+x y{3}=4.*x+x LegendText={'Location','SouthEast', 'Interpreter', 'latex','FontSize',16}; PlotOptions={'MarkerSize',5,'LineWidth',1,'DisplayName',FileName{i}} for i = 1:3 plot (x,y{i},PlotOptions); legend1 = legend('show','-DynamicLegend'); legend ([legend1, LegendText]) end I get the error on the pot diagram: Error using plot Conversion to double from cell is not possible. I think it is because I have a double value in the cell array (16). But I do not know how to avoid the error. Thanks a lot in advance for your help! Markus
Doug replied on : 12 of 15
@Markus, run using >>dbstop if error Once you hit the line with the error, try the command again, only simplifying it. So for instance, make PlotOptions contain only one Property Value pairing at a time. If you find one that works, then you can ignore it. Keep doing this until you find which P/V pair is the problem. Then play with it at the command line trying it with different inputs until you find out how it is misformed. You notice that it works for item 15 but not 16. This indicates you should look at the difference between the two iterations. Find the change and you will find the root cause and this will be the change you need to make. >>dbclear if error when you are done. Doug
Markus replied on : 13 of 15
Thanks again Doug for your help. The dbstop function is really practical. I found out now that the legend function does not accept all parameters in one cell array. Thus, do you know if there is a possibility to extract the cell array into single elements which are then read as single arguments by the legend function? Otherwise, I have to skip my idea and just go on with the "search and replace" command to change all Legend options in my m-file. Thanks again for your help!
Doug replied on : 14 of 15
@Markus, Specifically, what property value pairs are you trying to send to legend? Why does this require a cell array input? Doug
Markus replied on : 15 of 15
Hi Doug, sorry if I am not clear. I created the cell array because I wanted to put together several arguments of different types (strings and numbers) in one variable. Then I wanted to use this variable to be used when calling functions to pass all arguments from this variable also to the function. My partner for the project opened today also a thread on the Matlab Answers (https://www.mathworks.com/matlabcentral/answers/77326-how-to-store-function-parameters-in-a-single-variable). Maybe his explanation is a bit more clear. Thank you very much for your great help again!