So the output of my code produce many variables in every loop in Matlab workspace. I want to save two of the variables (namely MO and Vr) to a file having a fixed name with a number which change in every loop. The number which changes in each loop is "NT+1". First I change the name of the two desired variables with following code:
eval(sprintf('MO%d=MO;',NT+1));
eval(sprintf('Vr%d=Vr;',NT+1));
Now I want to save the renamed MO and Vr variables in a .mat file having the NT+1 number at the end. For instance, if NT+1=60, I want the the two renamed variables (which are MO60 and Vr60) be saved in a file having the NT+1 number at the end: sim60.mat
save('sim%d.mat','MO%d','Vr%d',NT+1)
hypothetical, the output of the above code should be a file named 'sim60.mat' having the two variables MO60 and Vr60.
How can I automatically perform such saving when the NT+1 changes in every loop and the name of MO and Vr also must be changed for the save command at each loop?
You should not rename the workspace variables because you will need to use eval
, which is almost always bad practice.
Go with
% create file name
flNm = num2str(i,'sim%d.mat');
% save file
save(flNm,'MO','Vr');
if you now load the file, load it to a struct
flNm = num2str(i,'sim%d.mat');
Dat = load(flNm,'MO','Vr');
% access the variables
Dat.Mo
Dat.Vr
usually one needs to load and save variables within a loop because the memory is too small to store them in a multidimensional array or a cell:
i_max = 10;
MO_all = NaN(3,3,i_max)
Vr_all = cell(i_max)
for i = 1:i_max
% what happens in every loop
MO = rand(3,3);
Vr = rand(randi(10),randi(10)); % changing size
% store for other loops
MO_all(:,:,i) = MO;
Vr_all{i} = Vr;
end
The solution to you particular question is
(I do not recommend using this as it is not flexible, not robust and requires eval
to create the variables in the first place!)
flNm = num2str(NT+1,'sim%d.mat');
vars2save = {num2str(NT+1,'MO%d'),num2str(NT+1,'Vr%d')};
save('sim%d.mat',vars2save {:})