Dynamic Variable Names in Matlab

Assume that you want to create a variable in Matlab whose name is contingent on factors that are unknown before the program runs.  For example, you may want to attach a time or date stamp to the end of a variable name.  You may also have variable names stored in a string or cell array that you want to instantiate as variables.  The best way to accomplish these tasks in Matlab is to use the eval function.  In the following examples, we’ll show you how to do these tasks.

Example 1:  Adding the time and date to a variable name

>> d = datestr(now, 'mmmm_dd_yy_HH_MM_SS');
>> eval(['data_' d ' = x;'])

Example 2:  Creating variables from strings

varnames = {'time', 'position', 'velocity'};
values = [2, 25.2, 3];

for k = 1:length(varnames)
     eval([varnames{k} '= ' num2str(values(k)) ';'])
end

Both of these examples use the eval function.  In example 1, the date and time are combined into one string which is appended to the end of a generic variable named data.  In example 2, the variable names are stored as strings that are contained in a cell array.  The values that will be saved in the variables are contained inside of a numeric array.  A for loop is used to save each value in the variable named in each string.

Notice in both of these examples that the eval function takes one string as an input and evaluates it as if it were a command typed into the command line.  Usually, this string is broken up into static and variable content.  Static content is placed inside of quotes, while variable content is outside of quotes and either entered as a variable name or enclosed within a num2str function.  The programmer must take care to check the syntax of the input string and visualize how the string will look during run-time in order to avoid errors.

3 thoughts on “Dynamic Variable Names in Matlab

  1. Very nice post. I just stumbled upon your weblog and wanted to say that I have truly enjoyed surfing around your
    blog posts. In any case I’ll be subscribing to your rss feed and I
    hope you write again soon!

  2. s a negative side to the rise in popularity of digital content, and that.
    A very convenient method to search for things on the web is
    to simply speak your quest term. We’ll start our tour at
    Marina Grande about the north shore of the island, about one third from the
    way in from the easternmost point.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.