Matlab – For loop running over different variables

matlab

Good day,

I would like to do the following in Matlab:

var1 = 10;
var2 = 15;
var3 = 20;

j = 1;

for i = [var1,var2,var3]
    a(j) = i + 10;
    j = j + 1;
end
clear j;

With result:

a(1) = var1 + 10 = 20
a(2) = var1 + 10 = 25 
a(3) = var1 + 10 = 30

Any ideas?

Best Solution

Engaging heavy use of crystal ball. It appears that you'd like to dynamically generate the names var1, var2, etc. Don't. There is just about never an advantage to naming variables this way. Use cell arrays instead:

var{1} = 10;
var{2} = 15;
var{3} = 20;

so that you can just use:

for i = 1:length(var)
    a(j) = var{i} + 10;
...

Note the curly brace.

If your variables are all the same size, it's even better to use array slices. var(:, i) or var(:,:,:,i), for example

Related Question