MATLAB Answers

Variable names in loop

11 views (last 30 days)
Rens Jochemsen
Rens Jochemsen on 24 May 2017
Commented: Jan on 24 May 2017
hi !
I want to create variable names in a loop, so A1, A2, A3 -- AN
something like
for i=1:N
A_i=whatever
end
I googled for it but only find answers from people that discourage you to use it, and use indexing instead. However, indexing is not quite an option for me, Because the A are already matrices.
I have a code that works, but at the moment, every line I have to repeat 5 times, for every dataset
data_norm_1=data1./max(data1)
data_norm_2=data2./max(data2)
data_norm_3=data3./max(data3)
etc
I just want one forloop
for i=1:5
data_norm_i = data_i./max(data_i)
end
I saw eval is proposed but i don't fully understand how to use it.
thanx in advance !
  3 Comments
Jan
Jan on 24 May 2017
@Rens: You noticed that you find only answers which suggest not to create variables dynamically with an index hidden in the name. You find many many many of these answers. They contain sentences like: "Don't do this" and "there is always a better solution". And then you insist, that indexing is not an option for you.
We have written hundrets of answers concerning this problem. And the answers are always the same. The problem does not concern Matlab only, but all programming languages, which allow to create variables dynamically. Remember that there are many languages, which do not allow this and of course you can solve all problems with them also.
Please, take the time to think twice. Many very experienced programmers tell you, that the only valuable and reliable option is not to do this. So please do your salf the favor and trust us. Hiding indices in the names of variables is a shot in your knee.

Sign in to comment.

Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!