MATLAB: How to make an image file path relative to an mlapp file that uses it

absoluteappdesignerMATLABpathrelative

I want to include an image in an App Designer app, The image file is in the same folder as the .mlapp file, but when I navigate the current MATLAB directory away from that folder and then run the app it doesn't find the image. How can I make the app always find the image no matter the current directory?

Best Answer

When given a relative file path, MATLAB will search the current directory and then the MATLAB path. When the current directory is a folder containing both the .mlapp file and an image file, 'icon.png', calling "uiimage(app.UIFigure, 'ImageSource', 'icon.png');" finds the image, but if the current MATLAB directory is different from that folder then it won't be found unless it is on the MATLAB path. The absolute file path can be hard coded, but this makes the app difficult to share between users. Commands like "pwd" also return the path to the current MATLAB directory, and not the path to the directory of the script that called it.
 
To obtain the absolute path to the image at run time, the following lines can be added to "startupFcn" in the .mlapp file:
 
imageFile = 'icon.png';
absPath = fileparts(mfilename('fullpath')); % absolute path to the folder containing the mlapp file
imageAbsolute = fullfile(absPath, imageFile); % absolute path to the image file
uiimage(app.UIFigure, 'ImageSource', imageAbsolute);