如何在 MATLAB 中将数字连接到变量名称? [英] How to concatenate a number to a variable name in MATLAB?

查看:24
本文介绍了如何在 MATLAB 中将数字连接到变量名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量a = 1.我想生成表单的变量名:

I have a variable a = 1. I want to generate a variable name of the form:

variableNumber  

所以在这个例子中,我想要

So in this example, I would want

a1
a2
a3

作为变量.我该怎么做?

as variables. How can I do that?

推荐答案

尝试 genvarname.

varname = genvarname(str)

是使用的基本语法.MATLAB 文档提供了使用此函数和排除列表的详细示例(用于确保唯一的变量名称).您将不得不使用 eval 或其他函数(例如 assignin,在前面的答案中提到)来利用这个变量名.

is the basic syntax for use. MATLAB documentation has detailed examples of using this function with an exclusion list (for ensuring unique variable names). You will have to use eval or another function (e.g. assignin, mentioned in an earlier answer) to utilise this variable name.

完整回答问题,

varnamelist = genvarname({'a','a','a','a','a'});
for l=1:length(varnamelist)
  eval([varnamelist{l} '= l^2']);
end

当然,有更有效的方法来为 genvarname 组合输入列表,这留作练习 ;)

Of course, there are more efficient ways of putting together an input list for genvarname, this is left as an exercise ;)

如果您关心性能,请注意 eval 可能会大大降低脚本/函数的速度;如果您需要动态变量命名,我个人建议使用结构或单元数据类型.

If you're concerned about performance, note that eval may slow down the script/function greatly; personally I would recommend the use of struct or cell datatypes if you need dynamic variable naming.

这篇关于如何在 MATLAB 中将数字连接到变量名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆