用字符串名称创建变量 [英] Create variables with names from strings

查看:84
本文介绍了用字符串名称创建变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我要创建10个看起来像这样的变量:

Let's assume that I want to create 10 variables which would look like this:

x1 = 1;
x2 = 2;
x3 = 3;
x4 = 4;
.
.
xi = i;

这是我打算做的简化版本.基本上,我只是想通过自动创建这些变量来节省代码行.是否可以在Matlab中构造变量名?在我的示例中,模式为["x", num2str(i)].但是我找不到一种使用该名称创建变量的方法.

This is a simplified version of what I'm intending to do. Basically I just want so save code lines by creating these variables in an automated way. Is there the possibility to construct a variable name in Matlab? The pattern in my example would be ["x", num2str(i)]. But I cant find a way to create a variable with that name.

推荐答案

您可以使用 eval ,但您确实应该

You can do it with eval but you really should not

eval(['x', num2str(i), ' = ', num2str(i)]); %//Not recommended

请使用单元格数组:

x{i} = i

这篇关于用字符串名称创建变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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