Main Content


Run MATLAB script



run(scriptname) runs the MATLAB® script specified by scriptname.


collapse all

Create a temporary folder that is not on your current path.

tmp = tempname;

Write MATLAB code to a file in the folder.

newFile = fullfile(tmp,'ANewFile.m');
fid = fopen(newFile,'w');
fprintf(fid,'Z = magic(5);\n');
fprintf(fid,'b = bar3(Z);\n'); 

Run the script.


Figure contains an axes object. The axes object contains 5 objects of type surface.

Input Arguments

collapse all

Name of MATLAB script, specified as a string scalar or character vector. scriptname can be any file type that MATLAB can execute, such as a MATLAB script file, Simulink® model, or MEX-file. scriptname can access any variables in the current workspace.

If scriptname is in the current folder or in a folder on the MATLAB path, specify just the name of the file.

If scriptname is not in the current folder or in a folder on the MATLAB path, specify the full or relative path of the file. Alternatively, you can use cd to change the current folder to the folder that contains the file, or use addpath to add the containing folder to the MATLAB path. Then, you can specify just the name of the file.


If scriptname corresponds to both a .m file and a P-file residing in the same folder, then run executes the P-file. This occurs even if you specify scriptname with a .m extension.

Example: run("myScript")

Example: run("anotherScript.mlx")

Example: run("C:\myFolder\myScript.m")

Example: run("myFolder\anotherScript.mlx")


  • To update the output when running live scripts, use the Run button in the Live Editor tab instead of the run function. The run function does not update live scripts with new output.

  • If you edit a script using an external editor, call clear scriptname in between calls to the run function in the same MATLAB session to make sure that the changed script is run. If a script is not on the MATLAB path, run caches the script when running it. Calling clear scriptname clears the cached version of the script and forces the run function to use the changed version of the script. If you edit the script with the MATLAB Editor, the run function always runs the changed version and there is no need to call clear scriptname.

  • run changes to the folder that contains the script, executes it, and resets back to the original folder. If the script itself changes folders, then run does not revert to the original folder, unless scriptname changes to the folder in which this script resides.

Version History

Introduced before R2006a