0

I have a number of vectors containing data that i have to elaborate in the same way, they are named in this fashion: "data1", "data2" ecc... I would like to automatize the process with a for cycle, how can i "select" iteratively the variables using the index? For example, the first line of my elaboration is an assignment like "x = data1", i want the second cycle to do "x = data2" and so on. Thank you in advance

Matteo Caruso
  • 37
  • 1
  • 7
  • 1
    It's much better to define one array `data` containing all your current variables as rows, cells, or fields. [Dynamic variable names are bad](https://stackoverflow.com/a/32467170/2586922). You should [keep data out of your variable names](https://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html) – Luis Mendo May 07 '18 at 13:42

1 Answers1

0

You can use a combination of strcat and num2str to create the name of the variable

i = 1;
name = strcat("data",int2str(i));

Thus putting it inside a for-loops which updates i will continuously change the name. Next you can use eval to evaluate the name

x = eval(name);

In total

for i = 1:n
    name = strcat("data",int2str(i));
    x = eval(name);
end

NOTE 1: It is in general considered bad practice to create variable names this way. You would have been much better off with saving all variables in the same array. As linked by Luis Mendo in the comments.

NOTE 2: It is generally recognised as a for-loop, not a for-cycle :D

Nicky Mattsson
  • 3,052
  • 12
  • 28