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?
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's value)_(x2's value) as a name.
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开发者_JAVA百科 above which I can assign a value to.
Any help would be greatly appreciated.
Take a look at the following FAQ:
- How can I create variables A1, A2,...,A10 in a loop?
It answers the "how" part of your question and recommends a better approach using arrays.
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));
If x1
and x2
are strings, this becomes:
x1 = 'foo';
x2 = 'bar';
newValue = 25;
eval(sprintf('x_%s_%s = newValue;',x1,x2));
or more simply (using concatenation instead of SPRINTF):
x1 = 'foo';
x2 = 'bar';
newValue = 25;
eval(['x_' x1 '_' x2 ' = newValue']);
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;
Assuming you have a really good reason why you'd want to do that (and assuming x1 and x2 have integer values), you can do this by combining EVAL and SPRINTF.
x1 = 3;
x2 = 4;
newValue = 25;
eval(sprintf('x_%i_%i = newValue;',x1,x2));
If x1 and x2 are floats, it'll be trickier since a variable name cannot have dots in it, though it would still be possible as long as you replace the dots with something else.
However, I really have to ask: Are you sure that you want to do that? Because at the moment I cannot imagine an application where would want to create variable names you don't know beforehand, which in turn makes it very hard to write an efficient program.
EDIT
There are many useful ways to store your data in arrays. If you really don't want that, you may be interested in accessing data via key/value pairs in a MAP, a feature which is available in more recent versions of Matlab. Thus, your key would become sprintf('%i_%i',x1,x2)
, and the corresponding value would be whatever it is you want to store.
You can also use dynamic field references. Loren at the Mathworks gives a writeup here:
Mathworks: use-dynamic-field-references
精彩评论