MATLAB: How to make UIGETFILE start up in the directory where I selected the previous file

dialogdirectoryfilefilterspecMATLABopenpathpersistentpreviousselectstartstartupuigetfilevariable

I have used the UIGETFILE to select files. I want the UIGETFILE dialog to open up in the directory where I selected my previous file.

Best Answer

One way to do this is to define the path to the selected files as PERSISTENT. For more information about PERSISTENT variables see:
>> doc persistent
It is possible to specify the path to the directory you would like the UIGETFILE functions to begin in, by specifying the path in the “FilterSpec” input argument. To do this, use the full path to the directory. For more information, see the related solution below.
This example shows how the UIGETFILE dialog will open up in the directory where the last file was selected from:
function testUigetfile
persistent lastPath pathName
% If this is the first time running the function this session,
% Initialize lastPath to 0
if isempty(lastPath) 
    lastPath = 0;
end
% First time calling 'uigetfile', use the pwd
if lastPath == 0
    [fileName, pathName] = uigetfile;
    
% All subsequent calls, use the path to the last selected file
else
    [fileName, pathName] = uigetfile(lastPath);
end
% Use the path to the last selected file
% If 'uigetfile' is called, but no item is selected, 'lastPath' is not overwritten with 0
if pathName ~= 0
    lastPath = pathName;
end