0

I would like to create a set of distinct variables in the form of e_1, e_2, e_3... The number of variables would depend on the value of k as shown below.

for i = 1:k

  "create variable" = e_"i";

end

I will then want to call these variables; hence, I would need another loop that would be able to assign the correct value to each variable created before, or pull something out of the variable.

dustin
  • 4,309
  • 12
  • 57
  • 79
user2565552
  • 45
  • 2
  • 6
  • `eval` could do this. But a cell array might be easier. – aschepler Jul 09 '13 at 17:34
  • 1
    Why would you want to do this? Using an array will do the same job, right? http://www.ele.uri.edu/Courses/ele541/tutorials/matlab.html – Tharindu Rusira Jul 09 '13 at 17:36
  • 1
    google it: http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F – user2482876 Jul 09 '13 at 17:48
  • 1
    possible duplicate of [How to concatenate a number to a variable name in MATLAB?](http://stackoverflow.com/questions/2809635/how-to-concatenate-a-number-to-a-variable-name-in-matlab), http://stackoverflow.com/q/16099398 – Amro Jul 09 '13 at 17:52
  • Thanks everyone, building a cell array solved the problem. – user2565552 Jul 09 '13 at 18:08
  • Generally it is not considered good practice in Matlab to use variables like that. **Always** consider exploiting vector, matrix, cell, struct formats! – Schorsch Jul 09 '13 at 18:18

2 Answers2

1

One option would be to do something like this:

kk = 10;
for ii=1:kk
  eval(['e_' num2str(ii) '=[];'])
end
m_power
  • 3,156
  • 5
  • 33
  • 54
-1

I got just the fix for you. Was just trying to do the same thing. Needed to be able to create an array with an infinate number of variables. Here's what I came up with. Well, I was adding 2 variables at a time, so it may be a little different than your version.

String[] parts;
String x = "";
String var = "";
int i = 0;
//to add variables
if(x.contains("-"){
 x+="-"+var;
}
else{
x+=""+var;
}

then to get them, u just use.

if(x.contains("-")){
parts = x.split("-");
while(i<parts.length){
  var=parts[i];
  i++;
 }
}
else if (x!=""){
var = x;
}

Changing the variables is a whole other story. I'll let your gifted mind figure that out. I don't need that part yet.

*hint, you're going to have to loop and put together the whole String back together with the new variables. Hope this helped. Felt like this was a new way of looking at it.

pete the pagan-gerbil
  • 3,136
  • 2
  • 28
  • 49
Forty
  • 19
  • 1