Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create variables with names from strings

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;

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.

like image 954
Potaito Avatar asked Apr 19 '13 07:04

Potaito


People also ask

How do you create a variable name from a string?

String Into Variable Name in Python Using the vars() Function. Instead of using the locals() and the globals() function to convert a string to a variable name in python, we can also use the vars() function. The vars() function, when executed in the global scope, behaves just like the globals() function.

How do you create a variable name from a string in MATLAB?

varname = genvarname(str) constructs a string or character vector varname that is similar to or the same as the str input, and can be used as a valid variable name. str can be a string, a string array, a character array, a cell array of character vectors.

Is variable name a string?

A string variable is a variable that holds a character string. It is a section of memory that has been given a name by the programmer. The name looks like those variable names you have seen so far, except that the name of a string variable ends with a dollar sign, $. The $ is part of the name.


2 Answers

You can do it with eval but you really should not

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

Rather use a cell array:

x{i} = i
like image 97
Dan Avatar answered Sep 30 '22 14:09

Dan


I also strongly advise using a cell array or a struct for such cases. I think it will even give you some performance boost.

If you really need to do so Dan told how to. But I would also like to point to the genvarname function. It will make sure your string is a valid variable name.

EDIT: genvarname is part of core matlab and not of the statistics toolbox

like image 41
bdecaf Avatar answered Sep 30 '22 16:09

bdecaf