MATLAB Language MATLAB Best Practices Create Unique Name for Temporary File


Example

While coding a script or a function, it can be the case that one or more than one temporary file be needed in order to, for example, store some data.

In order to avoid overwriting an existing file or to shadow a MATLAB function the tempname function can be used to generate a unique name for a temporary file in the system temporary folder.

my_temp_file=tempname

The filename is generated without the extension; it can be added by concatenating the desired extension to the name generated by tempname

my_temp_file_with_ext=[tempname '.txt']

The locaton of the system temporary folder can be retrieved by caling the tempdir function.

If, during the execution of the function / script, the temporary file is no longer needed, it can be deleted by using the function delete

Since delete does not ask for confirmation, it might be useful to set on the option to move the file to be deleted in the recycle folder.

This can be done by using the function recycle this way:

recycle('on')

In the following example, a possible usage of the functions tempname, delete and recycle is proposed.

%
% Create some example data
%
theta=0:.1:2*pi;
x=cos(theta);
y=sin(theta);
%
% Generate the temporary filename
%
my_temp_file=[tempname '.mat'];
%
% Split the filename (path, name, extension) and display them in a message box
[tmp_file_path,tmp_file_name, tmp_file_ext]=fileparts(my_temp_file)
uiwait(msgbox(sprintf('Path= %s\nName= %s\nExt= %s', ...
              tmp_file_path,tmp_file_name,tmp_file_ext),'TEMPORARY FILE'))
%
% Save the varaibles in a temporary file
%
save(my_temp_file,'x','y','theta')
%
% Load the varaibles from the temporary file
%
load(my_temp_file)
%
% Set the reclycle option on
%
recycle('on')
%
% Delete the temporary file
%
delete(my_temp_file)

Caveat

The temporary filename is generated by using the java.util.UUID.randomUUID method (randomUUID).

If MATLAB is run without JVM, the temporary filename is generated by using
matlab.internal.timing.timing based on the CPU counter and time. In this case the temporary filename is not guaranteed to be unique.