-2

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?

Pietair
  • 396
  • 2
  • 8
  • 18

3 Answers3

2

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

Peter
  • 14,559
  • 35
  • 55
0

There was a similar question with a successful answer: foreach loop with strings in Matlab

maybe use the cell array syntax with {}:

for i = {var1,var2,var3}
a(j) = i + 10;
j = j + 1;
end
Community
  • 1
  • 1
FloHin
  • 41
  • 1
  • 7
0

Both @FloHin and @Peter have mentioned using cells, which is a great method to help you when you have a limited number of non-scalar variables. In case you are dealing with unknown number of such variables that follow a certain format, you can use eval function to get the value of the current variable on-demand:

var1 = 10;
var2 = 15;
var3 = 20;
var4 = 30;
# ...
# more variables following the varN = x pattern

all_variables = who('var*');
num = numel(all_variables);
a = zeros(num, 1);
for i = 1:num
    a(i) = eval(all_variables{i}) + 10;
end
Bee
  • 2,472
  • 20
  • 26