mfilename

Returns the name of the file that is running.

Category: Programming > Functions

Syntax

name = mfilename

Returns the file name without path or extension.

p = mfilename('fullpath')

Returns the path including the file name, without the extension.

d = mfilename('fullpathext')

Returns the path including name and extension.

Description

Inside a function file, mfilename is the name of that file, which lets error messages or log lines name their origin without hard-coding it. Called from a script, it gives the script's name. When there is no file, as in code typed at the prompt, the result is empty.

Input arguments

'fullpath'
Option that adds the folder to the result.
'fullpathext'
Option that adds the folder and the extension.

Output arguments

name
Character vector; empty when called from the command line or from code with no file.

Example

A function reporting its own file name

writelines(["function r = who_am_i()", "  r = mfilename;", "end"], 'who_am_i.m');
who_am_i
Output
ans = 'who_am_i'

See also

fileparts which inputname