Save loop variable naming problem
이전 댓글 표시
I want to save the answers in the loop for future use, I understand that I can use sprintf to batch store the data in the variables, but if I want to change my name with the loop, how can I do it?
ex.
for i = 1:10
k(i) = 2^i
end
k =
2 4 8 16 32 64 128 256 512 1024
I want to name the variables separately as
k1 = 2
k2 = 4
k3 = 8
....
k10 = 1024
답변 (1개)
Image Analyst
2022년 8월 30일
0 개 추천
Please don't do that. It's a bad idea. Why not do it? See the FAQ:
댓글 수: 6
peter huang
2022년 8월 30일
"Because I may need to reload these data back to matlab plot in the future"
Much better code design would simply use exactly the same variable name in each file. Then your code would be simpler, more efficient, and much more robust.
"Would like to ask is there any way to write the loop in this process?"
Either by writing more of your complex code using dynamic variable names...
or by using exactly the same variable names in each file and writing simpler code.
"Or just do it one by one"
Computers are good at one thing: repeating simple tasks in loops. When you copy-and-paste code like that, you are just doing the computer's job for it.
You should avoid dynamic variable names.
peter huang
2022년 8월 30일
Image Analyst
2022년 8월 30일
You "solved" your problem in a bad way - they way we explicitly told you not to do:
eval(['moving_time_' num2str(i) '=plot_time;']);
First of all, if you have just a handful of variables, like 4 or less, it's fine to have separately named variables but just assign them immediately, by their known name, rather than in a loop and by using the hated eval().
However, if you have a large or variable number of variables, then create a 2-D array if they're all the same size, or a cell array if they (unfortunately) need to be of different lengths. For example
numVectors = 10; % or whatever it is.
moving_time = zeros(numVectors, vectorLength); % Preallocate space in advance.
for k = 1 : numVectors
thisMoving_time = plot_time; % Get the plot times for this iteration somehow.
moving_time(k, :) = thisMoving_time; % Store this time vector as row k of our 2-D array
end
% Save the 2-D array of all time vectors as a single variable in a single .mat file.
fullFileName = fullfile(pwd, 'moving_times.mat');
save(fullFileName, 'moving_time');
peter huang
2022년 8월 31일
Great, I think this method is much better than eval Then I would like to ask how the variable I want to access today is not 1*n, but may have 68*n and then 20 years of data every year.
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!