Using index to name variables

조회 수: 88 (최근 30일)
Lukas Netzer
Lukas Netzer 2021년 5월 12일
댓글: Lukas Netzer 2021년 5월 13일
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;
end
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!
  댓글 수: 2
Lukas Netzer
Lukas Netzer 2021년 5월 12일
one solution that would work is:
str1 = "a_" + tt{n};
str2 = "b_" + tt{n};
But as stated above, I have lots of those variables, is there maybe a better way?
Rik
Rik 2021년 5월 12일
Why do you want numbered variables? You shouldn't store data in a variable name.

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2021년 5월 12일
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;
end
end
  댓글 수: 1
Lukas Netzer
Lukas Netzer 2021년 5월 13일
Thank you very much - still alot to learn!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by