Matlab-如何根据其他变量的值命名新变量? [英] Matlab- How does you name a new variable based on other variables' values?

查看:139
本文介绍了Matlab-如何根据其他变量的值命名新变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复项:
如何在MATLAB吗?
MATLAB:如何使用变量另一个变量名中的值?

Possible Duplicates:
How to concatenate a number to a variable name in MATLAB?
MATLAB: How can I use a variables value in another variables name?

我想使用函数中给定的其他变量的值来命名变量. 因此,如果我有一个x1,x2的值,则可以将新变量的名称命名为:

I want to name a variable using values of other variables given in a function. So, if I have values for an x1,x2 I can make the new variable's name as:

x_(x1的值)_(x2的值)作为名称.

x_(x1's value)_(x2's value) as a name.

我已经检出了eval,num2str,strcat函数,但是到目前为止,我还无法做到这一点,因此我有了一个名称可以在上面分配值的变量.

I've checked out the eval, num2str, strcat functions, but as of yet I can't make it so that I have a variable with the name above which I can assign a value to.

任何帮助将不胜感激.

推荐答案

乔纳斯建议的,如果x1是有效的数字:

As Jonas suggests, if x1 and x2 are numbers this works:

x1 = 3;
x2 = 4;
newValue = 25;

eval(sprintf('x_%i_%i = newValue;',x1,x2));

如果x1x2是字符串,则变为:

If x1 and x2 are strings, this becomes:

x1 = 'foo';
x2 = 'bar';
newValue = 25;

eval(sprintf('x_%s_%s = newValue;',x1,x2));

或更简单(使用串联而不是SPRINTF):

or more simply (using concatenation instead of SPRINTF):

x1 = 'foo';
x2 = 'bar';
newValue = 25;

eval(['x_' x1 '_' x2 ' = newValue']);

我不知道您要完成什么,但这可能不是解决问题的最佳方法. EVAL应该始终避免.在使用EVAL中创建变量是(又称欺骗")是很糟糕的.

I don't know what you're trying to accomplish, but this probably isn't the best way to go about it. EVAL should always be avoided. Creating variables in the using EVAL is (a.k.a. "poofing") is doubly bad.

如果您尝试将参数与值相关联,请结构是更好的解决方案:

If you're trying to associate parameters with values, structures are a much better solution:

x1 = 'foo';
x2 = 'bar';
newValue = 25;

x.([x1 '_' x2]) = newValue;

这篇关于Matlab-如何根据其他变量的值命名新变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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