分享

Dynamic Variable Names in Matlab

 windycityboy 2014-07-18

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.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多