# Saving from inside a parfor loop in Matlab

If you call save from a parfor loop in Matlab, like this for example:

parfor k=1:100 foo = exp(-k); save(['myfile',num2str(k),'.mat'],'foo'); end

it will generate an error. I have not exactly figured out why this is but probably it has to do with the fluctuating nature of the foo variable inside the parfor loop. By calling a function with a filename and the variables you want to save as arguments you can get around this problem. By doing this I am guessing Matlab sees the variables as outside of the parfor block and no longer uncertain in value. The code would look something like this.

parfor k=1:100 foo = exp(-k); mySave(['myfile',num2str(k),'.mat'],foo); end   function mySave(fName, foo) save(fName,'foo'); end