0

If I have three variables called

var1 var2 and var3 in MATLAB ( I do not want to create them I have them )

I need to call for each of them and set them equal to 1.

I could write

var1 = 1;
var2 = 1;
var3 = 1;

But can I use a for loop?

For example (which doesn't run)

for i=1:3
var&i=1
end
user30609
  • 264
  • 1
  • 17
  • 4
    That's [bad](https://stackoverflow.com/a/32467170/2586922) [practice](https://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html). You can use an array or cell array `var`, which you can index as `var(i)` or `var{i}` – Luis Mendo Mar 18 '21 at 19:31
  • 3
    What Luis means is that you can redefine `var1, var2, ...` as `var{1}, var{2}, ...`, either by modifying the code that originally creates the variables or by running `var{1}=var1;var{2}=var2;...;clear var1 var2 ...;`. Then your loop becomes `for i=1:numel(var), var{i}=1; end`. – Vicky Mar 18 '21 at 19:46

1 Answers1

1
for i = 1:3
assignin('base',['var',num2str(i)],1)
end
  • 4
    While this is technically valid, the mindset behind this solution can lead OP (and other readers) to start liberally sprinkling their code with `assignin()`s, `eval()`s, globals, etc. That can eventually lead to security risks, performance degradation, unreadable code, debugging nightmares, etc. – Vicky Mar 18 '21 at 23:52
  • I agree. I just provide @user30609 the answer on his question. – geoinformatic Mar 19 '21 at 07:21