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:

  1. be sure, that in the window Current Folder (top left) you see a folder, in which you want to create the new folder
  2. 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), write mkdir MScripts)
  3. 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)
  4. 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:

  1. be sure, that in the window Current Folder you see a folder, in which you want to create the new script
  2. 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, write edit 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)
  3. write some Matlabs commands, for example
       A = 6;
       disp('value of the variable A is:')
       disp(A)
     
  4. save the file
  5. 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:

  1. be sure, that in the window Current Folder you have a folder, where you can see your script file - in our case, test1.m
  2. 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
  3. 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)
     
  4. save the file and run the script


Last updated 9. october 2017