MATLAB Scripts

Typing commands one at a time in the Command Window works for a quick check, but a calculation you will repeat, debug or hand in needs to live in a file. A MATLAB script is that file: a saved list of commands that MATLAB runs from top to bottom whenever you call it. You meet scripts in your first MATLAB lab, and they remain the standard way to package an analysis so that someone else can rerun it.

What a script is

A script is a plain-text file with the extension .m that contains MATLAB statements. Running it is equivalent to typing its lines into the Command Window in order. A script has no input or output arguments; it works directly with variables in the workspace where it runs. It can still print output and create or change workspace variables.


Here is a short script that evaluates the kinetic energy


KE=12mv2KE = \tfrac{1}{2} m v^2


for a vehicle whose mass has already been entered:


MATLAB
% ke_calc.m  Kinetic energy of a vehicle
v = 15;               % speed, m/s
KE = 0.5*m*v^2;       % kinetic energy, J
fprintf('Kinetic energy: %.1f kJ\n', KE/1000)


If you first type m = 1200; and then ke_calc, MATLAB prints Kinetic energy: 135.0 kJ, because 0.5×1200×152=135 000 J0.5 \times 1200 \times 15^2 = 135\,000\ \text{J}.

Naming, saving and running

You call a script by its file name without .m, so the name must be a valid MATLAB identifier: it starts with a letter and then uses only letters, digits and underscores, up to namelengthmax characters, subject to operating-system filename limits. Reserved MATLAB keywords, such as for and end, cannot be used as script names.


File name

Runs when you type its name?

Reason

ke_calc.m

Yes

Letters and an underscore

trial3.m

Yes

Digits are allowed after the first letter

ke-calc.m

No

MATLAB reads ke-calc as ke minus calc

3trial.m

No

The name starts with a digit

ke calc.m

No

The space splits it into a command and an argument


Three common ways to run a saved script:

  • type its name in the Command Window;
  • click Run in the Editor, which saves the file and then runs it;
  • call run('ke_calc.m').

MATLAB must be able to find the file, so keep it in the Current Folder or in a folder on the search path.



Scripts share the base workspace

When you run a script from the Command Window, it works in the base workspace, the same set of variables you see in the Workspace browser. It has no separate workspace of its own.


A Command Window, a script file and the base workspace, with arrows showing the script reading and writing workspace variables.


Three consequences follow:

  • The script can read any variable that already exists, such as m above. If a variable it needs is missing, it stops with an error that names it.
  • Every variable the script creates, here v and KE, is still there after it finishes, so you can inspect or plot it.
  • Running the script again starts from whatever the workspace holds now, not from a clean slate. A script that updates and reuses workspace inputs can produce different results on successive runs. Here, if m remains unchanged, rerunning ke_calc gives the same result because it assigns v = 15 each time.



Writing readable scripts

  • Start with a comment line giving the file name and purpose; help ke_calc displays that first comment block.
  • Put inputs near the top, one per line, each with its unit in a % comment.
  • End assignments with ; to suppress display; leave the semicolon off only for values you want echoed.
  • Split a long script into sections that begin with %%; the Editor's Run Section command runs one section at a time while you debug.

What to remember

  • A script is a .m file of commands that run in order. It has no input or output arguments, but can print output and create workspace variables.
  • Its name must be a valid identifier, exclude reserved keywords and avoid clashes with variables or functions you use.
  • A script run from the Command Window reads and writes the base workspace, and its variables persist after it ends.
  • A clear at the top of a script run from the Command Window erases the whole base workspace, not only the script's own variables.

Example: A flow-rate script

Water flows through a pipe of inner diameter 50 mm at a mean speed of 2.0 m/s. The volumetric flow rate is Q=vAQ = vA, where the flow area is A=πd2/4A = \pi d^2 / 4.


a) Write a script that stores the inputs in SI units, computes AA and QQ, and prints QQ in litres per second to two decimal places. State the line it prints.


Save the following as pipe_flow.m in the Current Folder:


MATLAB
% pipe_flow.m  Volumetric flow rate in a circular pipe
d = 0.050;            % inner diameter, m
v = 2.0;              % mean speed, m/s
A = pi*d^2/4;         % flow area, m^2
Q = v*A;              % flow rate, m^3/s
fprintf('Flow rate: %.2f L/s\n', Q*1000)


The semicolons keep the intermediate values from being echoed, so the fprintf line is the only output. The script computes


A=π(0.050 m)24=1.963×10−3 m2Q=(2.0 m/s)(1.963×10−3 m2)=3.927×10−3 m3/s\begin{aligned} A &= \frac{\pi (0.050\ \text{m})^2}{4} = 1.963 \times 10^{-3}\ \text{m}^2 \\ Q &= (2.0\ \text{m/s})(1.963 \times 10^{-3}\ \text{m}^2) = 3.927 \times 10^{-3}\ \text{m}^3/\text{s} \end{aligned}


Multiplying by 1000 L/m31000\ \text{L/m}^3 gives ________ L/s, so typing pipe_flow prints Flow rate: 3.93 L/s.


b) A classmate saves the same code as pipe-flow.m and types pipe-flow in the Command Window. Explain what happens and how to fix it.


MATLAB reads pipe-flow as the expression pipe - flow. It looks for a variable or function called pipe, finds none, and stops with an error that pipe is unrecognized; the file is never executed. The hyphen makes the name an invalid identifier.


The fix is to rename the file pipe_flow.m (letters, digits and underscores only, starting with a letter) and run it by typing pipe_flow.


c) After running your script once, you type v = 3.0; in the Command Window and run pipe_flow again. What does it print? Next you delete the line v = 2.0; from the script, save it, type v = 3.0; again and run the script. What does it print now?


First rerun: the script shares the base workspace, so it does see your v = 3.0, but its second line immediately overwrites it with v = 2.0. The calculation is unchanged and it prints Flow rate: 3.93 L/s. Afterward v in the workspace is ________ again.


After deleting the line, the script no longer assigns v, so it reads the value 3.0 from the workspace:


Q=(3.0 m/s)(1.963×10−3 m2)=5.890×10−3 m3/sQ = (3.0\ \text{m/s})(1.963 \times 10^{-3}\ \text{m}^2) = 5.890 \times 10^{-3}\ \text{m}^3/\text{s}


That is 5.890 L/s, so it prints Flow rate: 5.89 L/s. Whether a script assigns a variable itself or reads it from the workspace decides which value wins; make that choice deliberately for every input.

You are writing a script that finds the total load on a beam. Inside it, you call MATLAB's built-in sum function to add the point loads, and you want to run the script by typing its name in the Command Window. Which file name should you save it under?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A student is writing a script, allowable_load.m, that finds the largest axial load a solid round steel rod can carry at an allowable normal stress of 120 MPa. The workspace is empty when the script runs. MATLAB executes a script's statements from top to bottom, and each line below uses only variables that earlier lines create. Arrange the five lines in the order they must appear in the file, so that the script runs without an error and prints the allowable load.

  1. 1.

    fprintf('Allowable load: %.1f kN\n', F/1000)

  2. 2.

    D_mm = 40; % rod diameter, mm

  3. 3.

    A = pi*D^2/4; % cross-sectional area, m^2

  4. 4.

    F = 120e6*A; % allowable load, N

  5. 5.

    D = D_mm/1000; % rod diameter, m

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

In the Command Window you type k = 250;, a spring constant in N/m. You then run the script spring_force.m, saved in the Current Folder:


MATLAB
x = 0.12;       % extension, m
F = k*x         % spring force, N


Which statement describes what happens?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice