0
votes

Right now I am putting the simulation function together with the .mat containing simulation results and parameters in a .zip file. The file is then the final output of my simulation function. This procedure ensures I can track down mistakes - kind of a primitive version control. Simulation function is usually about 10-100 lines of code.

It would be more elegant if I could load a single file and get everything - so, I would like to create a single .mat file that contains both the code file as well as the variables, and when loaded to put that code file in the current folder when loading the data. Is that possible (doesn't seem to be - I can't find anything but saving variables and figures to .mat)?

Putting the whole contents of the function in a variable is a possible alternative I am considering, but I don't find it very compelling as I can't easily read that code until I re-create the file.

1

1 Answers

1
votes

The following assumes that the function that saves the simulation results is the same function that you want to store the code of. It works be using mfilename to get the file name, and then using evalc to capture the output of type to obtain its code:

function test
a = 1;
b = 2;
c = 1:10; % ... create result variables
code = evalc(['type ' mfilename]); % this variable stores the code of current function
save results % save in a file called 'results.mat'

Or, if you prefer to avoid evalc, you can read the file's contents with fread:

function test
a = 1;
b = 2;
c = 1:10; % ... create result variables
fid = fopen([mfilename('fullpath') '.m']); % open file of current function
code = fread(fid, '*char').'; % read its code
fclose(fid); % close file
clear fid % delete variable
save results % save in a file called 'results.mat'