MATLAB: How to save or load the variables to or from files with similar names

fileMATLABmultiplename

For example, within a FOR loop, I calculate values for my variables 'a', 'b', and 'c', ten times. I want to save these variables for each iteration to MAT-files with names test01.mat, test02.mat….test10.mat.

Best Answer

You can use string concatenation to create the strings for your filenames:
a = 1;
b = 2;
c = 3;
filename = 'test';
for i = 1:10
a = a + 1;
b = b + 2;
c = c + 3;
str_counter = num2str(i);
if i < 10
str_counter = ['0' str_counter]; %create '01' - '09' strings for 'test01.mat' - 'test09.mat'
end
new_filename = [filename str_counter]; %concatenate 'test' to the test number
save(new_filename,'a','b','c')
end
For more information on string concatenation, type
help horzcat
and
help strcat
at the MATLAB command prompt.
For information on how to import multiple files into the MATLAB workspace, see the Related Solution.