Create variables name with iteration number in each time step?
古いコメントを表示
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 件のコメント
BYUNGTARK LEE
2023 年 7 月 30 日
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
2023 年 7 月 31 日
編集済み: BYUNGTARK LEE
2023 年 7 月 31 日
回答 (1 件)
Walter Roberson
2023 年 7 月 29 日
0 投票
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
2023 年 7 月 30 日
Walter Roberson
2023 年 7 月 30 日
If you are "recording" as text display, then you can construct the text display with an appropriate character vector instead of needing it to be the name of a variable.
If you are "recording" by saving the variables to a file, then you can use dynamic structure field names and save() with the -struct option.
for k = 1:5
DNs.("DN_" + k) = k;
end
save(FILENAME, '-struct', 'DNs');
BYUNGTARK LEE
2023 年 7 月 31 日
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.
カテゴリ
ヘルプ センター および File Exchange で Structures についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!