Using index to name variables

3 views (last 30 days)
Lukas Netzer
Lukas Netzer on 12 May 2021
Commented: Lukas Netzer on 13 May 2021
I'm running a script with a index containing:
t{1} = Location1;
t{2} = Location2;
t{3} = Location3;
tt{1} = "Location1";
tt{2} = "Location2";
tt{3} = "Location3";
t's are tables. Now the actual script does e.g. this:
for x = 1:1:size(t{n})
if t{n}.var1(x) == 0
a_tt{n}(x) = b_tt{n}(x) / t{n}.var2(x);
if t{n}.var2(x) == 0
a_tt{n}(x) = 0;
As can be seen above I am trying to get a_Location1 and b_Location2 - but it does not work that way. Is there a smooth way to get a_location1/2/3 and b_location1/2/3 using the index?
It's for a lot of lines in the script, so some way without doing it by hand, would be nice!
Thanks for your help!
Rik on 12 May 2021
Why do you want numbered variables? You shouldn't store data in a variable name.

Sign in to comment.

Accepted Answer

Jan on 12 May 2021
Do not create variables names dynamically. This would store information in the names, where it is hard to access. Use the values of the variables instead.
You can use dynamic field names of structs:
a = struct()
for x = 1:1:size(t{n})
if t{n}.var1(x) == 0
a.(tt{n})(x) = b_tt{n}(x) / t{n}.var2(x);
elseif t{n}.var2(x) == 0
a.(tt{n})(x) = 0;
  1 Comment
Lukas Netzer
Lukas Netzer on 13 May 2021
Thank you very much - still alot to learn!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by