Continue to Site

# variable assignment in MATLAB

Status
Not open for further replies.

#### a_ronagh

##### Junior Member level 3
Hi
I have a problem in assigning a large number of variables with increasing indices.
Here is a simple example which shows exactley what I want:

var1=a; % a,b,... are are numbers or outputs of some functions
var2=b;
var3=c;
.
.
.
var100=z;

How can I do such an assignment in a for loop.I DON'T WANT TO USE ARRAYS.

What is the answer if a,b,c,... are outputs of functions which are named by
indices themselves.For example fun1(x1,x2,...),fun2(x1,x2,...),...

In fact my question is how to creat indices and add them to the name of variables and
functions?

Thank you so much for your help.

#### steve10

##### Full Member level 3
I believe the following is something you may want to try, and results are saved in a file "myresults.txt" in your work directory:

file_out=fopen('myresults.txt','w');
for i=1:max_num
a_number=some_number;
fprintf(file_out,'var%d = %10.5f',i,a_number);
end;
fclose(file_out);

Sorry, I don't have 'matlab' handy.

### a_ronagh

Points: 2

#### irfan1

##### Full Member level 5
you may use the eval function. the for loop may look like
Code:
for i=1:100
m=['var',int2str(i),"=fun",int2str(i),"(x1,x2,x3,x4,x5......)"];
eval m;
clear m;
end

We first create our string...for instance for the first run m will be a string holding var1=fun1(x1,x2,x3....) . Then using the eval function, we tell the matlab that the sting m is holding a command and we tell him to execute that command. I hope this helps

### a_ronagh

Points: 2

#### a_ronagh

##### Junior Member level 3
The answer of "irfan1" is definitely what I wanted and I learned something else