MATLAB: How to save variables with in the function with a new file name with every iteration.

save_variable_function

I tried to save my work space with a different file name for every iteration but it doesn't save any variable inside the function.? I want to save the variables of the function in every iteration.
As I am calling a function Hexagon so it runs for 20 seconds and it generates some output so I want to save work space of Hexagon function with a file name start with MS_Num and then MS_Num value every time it takes.
clc
clear all
close all
sizeL = 100;
radius = 10;
Num_MS = [1500 2000 3000 4000 5000 6000 7000 8000 9000 10000];
for i = 1 : 10
MS_Num = Num_MS(i);
Hexagon(sizeL,radius,MS_Num);
end
I will be happy if you can guide me. Thanks

Best Answer

Well you're not constructing a file name at all, and of course you're not then using that file name in a call to save() at all, so it's not surprising that no variables get saved to a file. Please see the FAQ for sample code to do what you want:
You'll see you can call sprintf() inside the loop to create a filename, then use save
for i = 1 : 10
MS_Num = Num_MS(i);
Hexagon(sizeL,radius,MS_Num);
thisBaseFileName = sprintf('MS_Num%d.mat', MS_Num);
fullFileName = fullfile(pwd, thisBaseFileName);
save(fullFileName, 'var1', 'var2', 'var3'); % Whatever variables you want.
end
Replace 'var1', etc. with the names of whatever variables you want to save in the mat file.