Skip to main content
Logo image

Section 5.1 Creating Script Files

Some notes about script files (M-files) to get us started:
  • A script file consists of a sequence of MATLAB commands.
  • Commands are executed in the order they are written just as if they were typed at the prompt.
  • Output (echoing) is still displayed to the Command Window.
  • Script files can be edited using any editor, i.e. your favorite - text edit, vim, Emacs, etc. Or you can use MATLAB’s built-in editor (super convenient since the editor provides some additional functionality).

Subsection 5.1.1 Editing Script Files

In MATLAB, script files are created and edited in the Editor/Debugger Window.
From the MATLAB menu: Home > New > Script
Or use your own editor and: File > Open
Either way a new Editor/Debugger Window will appear.
Try it out right now: open an empty file in the MATLAB editor and paste in the circuit code we created in the previous section:
V1 = 20; V2 = 12; V3 = 40;   % create voltages (V)
R1 = 18; R2 = 10; R3 = 16;   % create resistances
R4 = 6;  R5 = 15; R6 =  8;   %   (Ohms)
R7 = 12; R8 = 14;

% create resistance matrix R
R = [-(R1+R2+R3)
R2 R3 R2 -(R2+R4+R5+R7)
R4 R7 R3 R4 -(R3+R4+R6)
R6 0 R7 R6 -(R6+R7+R8)];

V = [-V1; 0; V2; -V3];
I = R\V;
I(3)-I(4)
Save this code under the name circuit.m.

Subsection 5.1.2 Running / Debugging Script Files

There are many different ways to run your script file. The most straight-forward one from within the editor is to simply click on the “run” button in the MATLAB editor.
Window showing how to run a script file
Figure 5.1. Running a script file
You can also run a script file from the Command Window prompt. If you script file is named circuit.m, for example, either of the following lines would run the script file:
>> run circuit
>> circuit
In any case, the .m extension is assumed.
As shown in the above image, it is possible to set “breakpoints” at which MATLAB will pause execution of the script file so that you can examine values of variables and make sure your code does what you expect it to do. It’s a great way to debug your code. Give it a try!
You set a breakpoint by clicking on the space to the left of the relevant line in the editor. You delete a breakpoint by clicking on it again.