hs100
hs100

Reputation: 496

Set compiled matlab GUI folder

I have a Matlab GUI (I compile it) that in order to load a file I press a button that uses this line

[file, folder] = uigetfile({'*.jpg;*.gif;*.bmp','All Image Files'},' Select image');

If I press the button again it opens the folder where the software is installed. How can I change it that it will remember and open the last folder I used?

Thanks.

Upvotes: 0

Views: 172

Answers (2)

sco1
sco1

Reputation: 12214

Per the documentation for uigetfile, you can specify an optional third input argument, DefaultName:

[FileName,PathName,FilterIndex] = uigetfile(FilterSpec,DialogTitle,DefaultName) displays a dialog box in which the file name specified by DefaultName appears in the File name field. DefaultName can also be a path or a path/filename. In this case, uigetfile opens the dialog box in the folder specified by the path. You can use .,..,\, or / in the DefaultName argument. To specify a folder name, make the last character of DefaultName either \ or /. If the specified path does not exist, uigetfile opens the dialog box in the current folder.

You can store the last opened folder to your GUI and access it when the button callback is fired.

For example:

function testgui
h.f = figure('MenuBar', 'none', 'NumberTitle', 'off', 'ToolBar', 'none');
h.b = uicontrol('Parent', h.f, 'Style', 'pushbutton', 'Units', 'Normalized', ...
                'Position', [0.1 0.3 0.8 0.4], 'String', 'Pick a file');
h.l = uicontrol('Parent', h.f, 'Style', 'text', 'Units', 'Normalized', ...
                'Position', [0.1 0.1 0.8 0.1], 'String', '');
setappdata(h.f, 'lastfolder', '');
h.l.String = sprintf('Last Directory: %s', '');

h.b.Callback = @(o, e) abutton(h);
end

function abutton(h)
lastfolder = getappdata(h.f, 'lastfolder');
[file, folder] = uigetfile({'*.jpg;*.gif;*.bmp','All Image Files'},' Select image', lastfolder);

if folder ~= 0
    setappdata(h.f, 'lastfolder', folder);
    h.l.String = sprintf('Last Directory: %s', folder);
end    
end

yay

Note that this approach resets to your current directory when the GUI is closed and reopened.

Upvotes: 2

Matt
Matt

Reputation: 2802

The folder output from uigetfile is the path that was selected. Use this as the input to the next call to uigetfile

[file, folder] = uigetfile({'*.jpg;*.gif;*.bmp','All Image Files';},...
            'Select Image', folder);

This is an example from doc uiputfile but it works with uigetfile as well.

Upvotes: 0

Related Questions