Table of Contents
What Script Files Are in MATLAB
In MATLAB, a script is a plain text file that contains a sequence of MATLAB commands. When you run the script, MATLAB executes those commands in order in the current workspace, as if you had typed them one by one in the Command Window.
Script files have the file extension .m. Any .m file that does not start with a function definition line is treated as a script. Scripts are useful when you want to automate repetitive tasks, collect related commands in one place, or save your work in a reproducible form.
Scripts do not have their own separate workspaces. All variables that a script creates or modifies live in the base workspace, which is the same space used by the Command Window.
Creating a New Script File
You can create a script in several ways from within the MATLAB Desktop. The most common starting point is the Home tab on the toolstrip. Clicking New Script opens a new file in the Editor, ready for you to type MATLAB code.
You can also create a new script from the Editor itself by choosing to create a new file. Another option is to use the command line. You can open a blank new script directly from the Command Window with the edit function:
editThis command opens an untitled script in the Editor. You can then write your code and save it with a meaningful name.
If you already know the name you want, and a file with that name does not exist, you can use:
edit myScript
If myScript.m does not exist, MATLAB creates it and opens it in the Editor. If it does exist, MATLAB opens the existing file instead.
Naming and Saving Script Files
When you save a script, you must choose a file name and a location. The file name becomes the script name, and MATLAB refers to the script without the .m extension. For example, if you save a script as analysis.m, you run it by typing analysis or pressing Run in the Editor.
Script names must follow the basic rules for MATLAB identifiers. They must start with a letter and can contain letters, digits, and underscores, but no spaces or special punctuation. Avoid using names that match MATLAB built in functions or keywords. For instance, naming a script mean.m or sum.m can cause confusion, because MATLAB may run your script instead of the intended built in function.
The file location also matters. MATLAB can run a script only if it is in the current folder or on the search path. When you save a new script, pay attention to the current folder shown in the Current Folder panel or in the address bar. If you save the file in a different location, you may need to navigate to that folder or adjust the path before MATLAB can find and run the script.
To save in the Editor, use the toolbar button or the usual keyboard shortcut for saving. MATLAB automatically adds the .m extension if you omit it.
Writing Code in a Script
Inside a script file, you can write any sequence of valid MATLAB commands. Each line is usually one statement, but long statements can continue on the next line with ... if needed.
You can add comments to explain what your script does. In MATLAB, a comment begins with the percent character % and continues to the end of the line. Comments are ignored when the script runs. For example:
% Compute the area of a circle for a given radius
radius = 5; % radius in units
area = pi * radius^2; % area formula
You can also use % to add temporary notes or to comment out lines of code that you do not want to execute at the moment.
If the first consecutive block of lines in your script consists of comments, MATLAB treats these as the script help text. This text appears when you use the help command with the script name. For example, if the top of circleArea.m looks like this:
% CIRCLEAREA Compute the area of a circle.
% CIRCLEAREA computes and displays the area of a circle
% for a fixed example radius value.
then calling help circleArea in the Command Window displays those comment lines.
Running Scripts from the Editor
The MATLAB Editor provides several ways to run a script. The most direct is the Run button in the Editor toolbar. When your script file is active, clicking Run executes the entire script from top to bottom.
When you run a script from the Editor, MATLAB automatically uses the folder that contains the script as the current folder for that run. This behavior applies as long as the file is on the path or accessible. It lets the script access files and data that are stored in the same project directory.
You can also run a script and provide it with input values indirectly by editing the code before you press Run. Scripts do not accept input arguments in the same way that functions do, so any values they use must come from the base workspace or be set inside the script itself. If you want a script to use different values, change those assignments in the script file, then run it again.
When the script runs, any output that is not terminated with a semicolon appears in the Command Window. For instance, if a line is x = 10 without a trailing semicolon, MATLAB displays the value of x when it executes that line. If the line ends with a semicolon, MATLAB performs the computation quietly.
Running Scripts from the Command Window
You can also run any script directly from the Command Window. Type the script name without the .m extension and press Enter:
myScript
MATLAB searches the current folder and the search path for a file named myScript.m. If it finds such a file and it is a script, MATLAB executes the script in the base workspace.
If MATLAB cannot find a script with that name, it reports an error that the function or variable is undefined. Often this means that either you mistyped the name, or the script file is not in the current folder or on the path.
The order in which MATLAB searches for a name is important. If you have a script and a function with the same name, MATLAB uses a specific search order that can cause it to run something other than what you expect. To avoid confusion, use unique names and do not reuse names of built in functions or other files in your project.
Running scripts from the Command Window is useful once your script is written and tested, because you can quickly rerun it without opening the Editor.
Interaction Between Scripts and the Workspace
When a script runs, it creates and modifies variables in the base workspace. If a variable already exists with the same name, the script overwrites its contents. If the variable does not exist yet, the script creates it. When the script finishes, the variables remain in the workspace, and you can inspect or use them interactively.
For example, if you have a variable a in the Command Window and your script contains the line a = 5;, then after running the script, a in the base workspace will have the value 5. This behavior can be convenient when you want the script to build up results for further exploration, but it can also lead to unexpected behavior if a script unintentionally depends on or changes existing variables.
Because scripts run in the base workspace, they can access any variables that are already present there. This includes variables you defined manually in the Command Window or that were created by other scripts you ran earlier. This can be helpful during exploratory work, but for more controlled behavior you need to be aware of this interaction.
If you want to prevent old variables from affecting your script, you can explicitly clear them at the start of the script using commands that remove variables. This practice can make your script more repeatable, since it always starts from a known state.
Viewing and Editing Scripts
Once you have saved a script, you can reopen it for viewing or editing. The simplest way is to locate the file in the Current Folder panel and double click it. MATLAB opens the file in the Editor. You can also right click a file and select an option to open it.
Another method is to use the edit command from the Command Window:
edit myScript
If myScript.m exists and is visible on the path or in the current folder, MATLAB opens it for editing. This is a quick way to jump into a file when you know its name.
The Editor displays line numbers which are useful for navigating and for interpreting error messages that reference specific lines in your script. You can modify code, add or remove lines, and save your changes. The next time you run the script, MATLAB uses the updated content.
While you edit a script, MATLAB may display small markers in the Editor margin to indicate code issues or suggestions. These tools belong to the code analysis and debugging features, which are covered separately, but they can already help you write scripts that MATLAB can run without syntax errors.
Running Only Parts of a Script
Although the default behavior is to run an entire script, the Editor also lets you run selected portions. This is useful when you are developing a script and want to test a specific section without executing everything.
To run a part of a script, highlight the lines you want, then select the option in the Editor toolbar that runs the selection. MATLAB executes only the highlighted commands in the base workspace. Any variables created or modified in that selection behave the same as when running the full script, they appear in the base workspace.
You can also place the cursor on a single line and run just that line, depending on your Editor configuration. This provides a quick way to experiment with small code changes while still keeping your code organized inside a script file.
For more structured control over sections within a script, MATLAB supports code sections that you can run independently, which is covered separately in the chapter about sectioning code and running sections.
Common Issues When Creating and Running Scripts
When you start creating scripts, a few common issues can prevent them from running as expected.
A frequent issue is a mismatch between the file name and what you type in the Command Window. Since MATLAB expects the script name to match the file name exactly, including case on some systems, MyScript.m and myscript.m might be treated as different files. Always run the script using the exact file name without the .m extension.
Another common issue is attempting to run a script that is not in the current folder or on the search path. If you see an error that the script is undefined, check the Current Folder panel to confirm you are in the correct location, or use appropriate commands to change the current folder to where your script resides.
Syntax errors in the script can also stop execution. If MATLAB encounters an invalid line, it will display an error message and stop running the script at that point. The message usually includes the file name and line number. You can open the script, go to that line, and correct the error.
Finally, if a script uses variables that are not defined anywhere, or depends on files that are not available, MATLAB will error when it reaches those lines. To diagnose these issues, make sure that all required variables are given values inside the script or are present in the base workspace before you run it, and that any external data files are in accessible locations.
Important points to remember:
Script files are plain text .m files that contain MATLAB commands and run in the base workspace.
The script name must be a valid MATLAB identifier and should not shadow built in functions.
To run a script, it must be in the current folder or on the path, and you call it by its name without .m.
Scripts create and modify variables in the base workspace, so existing variables can affect their behavior and vice versa.
You can create, edit, and run scripts efficiently from the MATLAB Editor, and you can also run them directly from the Command Window.