How to create a script (M-file) in Matlab
Creating a new folder
First of all, create a folder at your computer, where you will have all your Matlab scripts you create during this tutorial. Let us suppose its name will be MScripts. Then add the new folder to the search path:
- be sure, that in the window Current Folder (top left) you see a folder, in which you want to create the new folder
- create the new folder: right-click on the window Current Folder and choose New Folder, then type in its name MScripts
(or, in the Command Window (center), writemkdir MScripts
) - move to the new folder: double-click on the name of the folder in the window Current folder (or, in the Command Window write
cd MScripts
) - add the new folder to the search path: select the folder in the window Current folder, right-click and then select Add to Path
Creating a new script file (M-file)
Let us create a simple test script named test1, which just writes some number on the screen:
- be sure, that in the window Current Folder you see a folder, in which you want to create the new script
- create the new script: right-click on the window Current Folder, choose New File and then Script, then type in its name test1
(or, in the Command Window, writeedit test1
- this opens a blank file named test1.m;
if you chose a name of a file which already existed, this existing file would be opened instead of creating a new file) - write some Matlabs commands, for example
A = 6; disp('value of the variable A is:') disp(A)
- save the file
- run the script: in the Command Window, write
test1
(i.e. the name of the M-file, without the .m suffix)
Editing a script file (M-file)
Let us change our test script test1, so that it asks for two numbers and writes their sum to the screen:
- be sure, that in the window Current Folder you have a folder, where you can see your script file - in our case, test1.m
- open the script: either double-click on the name of the script in the Current Folder window, or write
edit test1
in the Command Window - rewrite the commands as:
A = input('give the first value: '); B = input('give the second value: '); C = A + B; disp('the sum is: ') disp(C)
- save the file and run the script