Create variables name with iteration number in each time step?

조회 수: 4 (최근 30일)
BYUNGTARK LEE
BYUNGTARK LEE 2023년 7월 29일
댓글: Walter Roberson 2023년 7월 31일
k =0;
for Timestep = 1:3
for k = 1:5
DN(1,k) = k
end
% here I want to make variable names DN_1, DN_2, DN_3, DN_4 and DN_5 with different Timestep so, DN_1(Timestep), ..., DN_5(Timestep).
% DN_1(Timestep) = DN(1,1);
% DN_2(Timestep) = DN(1,2);
% DN_3(Timestep) = DN(1,3);
% DN_4(Timestep) = DN(1,4);
% DN_5(Timestep) = DN(1,5);
end
% I can generate DN_1, .., DN_5 with genvarname but I cannot make them as arrays.
% Thanks in advance if you have any good idea.
  댓글 수: 4
Stephen23
Stephen23 2023년 7월 30일
"But I am using this variables just for recording purpose. I am not using these variables in calculations."
It makes no difference what you are using data for, the simple and effiicient approach is to use indexing into one array.
BYUNGTARK LEE
BYUNGTARK LEE 2023년 7월 31일
편집: BYUNGTARK LEE 2023년 7월 31일
I understand that it is better to avoid this, but I need a solution.

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

답변 (1개)

Walter Roberson
Walter Roberson 2023년 7월 29일
Please read http://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval for information about why we strongly recommend against creating variable names dynamically.
  댓글 수: 4
BYUNGTARK LEE
BYUNGTARK LEE 2023년 7월 31일
But DN_1 is not the variable I want. I need to define array DN_1(Timestep) ~ DN_5(Timestep). I want to record DN_1 ~ DN_5 in each timestep.
Walter Roberson
Walter Roberson 2023년 7월 31일
For the sake of discussion, write code as if you could access variable names using a syntax such as
DN_<k>(timestep) = value
with the <k> intended to show a dynamic variable name .
This syntax does not exist in MATLAB, but if you were to write demonstration code for us showing us exactly which dynamic variable names you want to use and where, then one of the volunteers can show you how to convert that into MATLAB code.

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

카테고리

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

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by