打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Dynamic Variable Names in Matlab
2
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)) ';'])endBoth 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.
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Matlab eval()函数使用
ruby系列教材(19):Variables
20 awk examples
利用Matlab对excell进行操作
matlab中字符串的替换 -
Meta Programming - Ruby-tw
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服