A script is a file that contains MATLAB code. When you run a script, MATLAB executes the commands in it, one after another, exactly as if you had typed them at the prompt. Scripts are also sometimes called M-files because they use the extension .m, short for MATLAB.
You can create scripts with any text editor or word processor, but the simplest way is to click the New Script button in the upper-left corner of the MATLAB interface, which opens a text editor designed for MATLAB.
To try it out, create a new script and enter the following code:
x = 5
Then press the Save button. A dialog window should appear where you can choose the filename and the folder where your script will go. Change the name to myscript.m and save it into any folder you like.
Now click the green Run button. You might get a message that says the script is not found in the current folder. If so, click the button that says Change Folder and it should run.
You can also run a script by typing its name in the Command Window and pressing . For example, if you enter
myscript, MATLAB should execute your script and display the result:
>> myscript x = 5
There are a few things to keep in mind when using scripts. First, you should not include the extension .m when you run a script. If you do, you’ll get an error message like this:
>> myscript.m Undefined variable "myscript" or class "myscript.m".
Second, when you name a new script, try to choose something meaningful and memorable. Don’t choose a name that’s already in use; if you do, you’ll replace one of MATLAB’s functions with your own (at least temporarily). You might not notice right away, but you might get some confusing behavior later.
Also, the name of the script cannot contain spaces. If you create a file named my script.m, MATLAB will complain when you try to run it:
>> my script Undefined function or variable 'my'.
It can be hard to remember which folder a script is in. To keep things simple, for now, I suggest putting all of your scripts in one folder.