Skip to main content
Logo image

Subsection Scripts

A MATLAB script is a .m file that stores a sequence of MATLAB commands. When you run the script, MATLAB reads the file from top to bottom and executes each command in order. Scripts let you save work you would otherwise type in the Command Window so you can rerun it quickly.

Script Structure.

Scripts are a first step toward thinking programmatically: instead of typing commands one at a time in the Command Window, you write a repeatable recipe that you can run again and again to get the same results. This also helps you organize work into clear stages: define inputs, perform computations, and display results.
Listing 15. A Generic MATLAB Script
% Script: example_script.m
% Purpose: Demonstrate a repeatable sequence of commands.

% 1) Set up a clean run
clc;
clear;

% 2) Define inputs (numbers you choose)
input1 = 10;
input2 = 3;

% 3) Compute results
result = input1^2 + 2*input2;

% 4) Display final results
fprintf('Result = %g\n', result);

πŸ“: β€œRunning” a Script.

A script shares the same workspace as the Command Window. That means variables created in the script appear in the Workspace after the script runs, and existing variables in the Workspace can affect a script if you rely on them. This is why scripts often begin with clear to avoid old values.
Later, we will introduce functions, which take inputs and produce outputs in separate workspaces. For now, scripts help us practice building a correct sequence of commands.

Reporting Results with fprintf.

Scripts often need to communicate results to a user. The simplest way to do this is to type a variable name or use disp. For more polished output, use the fprintf command.
The fprintf command is a very useful tool for sending messages to the Command Window from your program. The general pattern is:
fprintf('text with placeholders', value1, value2, ...);
The β€œplaceholders” start with a percent sign and indicate how MATLAB should display each value. Here are the most common ones:
  • %i for integers (whole numbers)
  • %f for decimal (fixed-point) numbers
  • %g for a compact numeric format (often a good default)
  • %s for text
You can control rounding by specifying the number of digits after the decimal point. For example, %.2f prints two digits after the decimal.
r = 4.5;
C = 2*pi*r;
A = pi*r^2;

fprintf('Radius r = %.2f\n', r);
fprintf('Circumference C = %.3f\n', C);
fprintf('Area A = %.3f\n', A);
Two special characters are especially common in formatted output:
x = 12;
y = 3.4567;
fprintf('x:\t%d\n', x);
fprintf('y:\t%.2f\n', y);
You can also control spacing with a field width. For example, %8.2f uses a field that is 8 characters wide. This helps align columns.
a = 2;
b = -4;
c = -6;

fprintf('Coefficients:\n');
fprintf('%8s %8s %8s\n', 'a', 'b', 'c');
fprintf('%8d %8d %8d\n', a, b, c);
To print a percent sign, use %%.
p = 0.237;
fprintf('Success rate: %.1f%%\n', 100*p);
The activities below use fprintf. Before moving on, paste these examples into MATLAB to become more familiar with the command.

πŸ§‘πŸ»β€πŸ’» Class Activities πŸ§‘πŸ»β€πŸ’» Class Activities

As you practice writing scripts, notice the repeated pattern: choose inputs, compute results, and report output. In the next step, functions will let us package that pattern into reusable tools that can accept inputs and return outputs.

1. Circle Report Script.

Write a script that computes the circumference and area of a circle from its radius, then prints a formatted report.
(b)
Define a radius variable r (starting with \(r = 4.5\)).
Solution.
% Selected Value
r = 4.5;
(c)
Compute the circumference \(C = 2\pi r\) and area \(A = \pi r^2\text{.}\)
Solution.
% Computations
C = 2*pi*r;
A = pi*r^2;
(d)
Print a clean report with three decimal places.
Solution.
% Display Results
fprintf('Circle report\n');
fprintf('Radius:        %.3f\n', r);
fprintf('Circumference: %.3f\n', C);
fprintf('Area:          %.3f\n', A);
(e)
Change r to a new value (such as \(10\)) and run again.
Solution.
Your script should automatically update the report whenever you change the input.

2. Temperature Conversion Script.

The conversion formula between Fahrenheit and Celsius is:
\begin{equation*} \text{tempC} = (\text{tempF} - 32)\cdot \frac59 \end{equation*}
Write a script that converts a temperature from Fahrenheit to Celsius and use fprintf to print some relevant messages to the command window.
(b)
Define a variable tempF for the temperature in Fahrenheit and start it at \(77^{\circ}\)F.
Solution.
% Selected Values
tempF = 77;
(c)
Compute the corresponding Celsius temperature and print both values using fprintf, rounding to one decimal place.
Solution.
% Computation
tempC = (tempF - 32) * (5/9);
% Display results
fprintf('Temperature: %.1f F = %.1f C\n', tempF, tempC);
(d)
Rerun the script with different temperatures (e.g., \(32^{\circ}\)F, \(100^{\circ}\)F).
Solution.
Your output should show \(32\) F corresponds to approximately \(0\) C, and \(100\) F corresponds to approximately \(37.8\) C.

3. Projectile Height Script.

A projectile’s height \(h(t)\) at time \(t\) seconds is given by the formula:
\begin{equation*} h(t) = h_0 + v_0 t - \tfrac12 g t^2\text{,} \end{equation*}
with parameters:
  • \(h_0\) is the initial height (in meters),
  • \(v_0\) is the initial velocity (in meters per second), and
  • \(g = 9.81\) m/s2 is the acceleration due to gravity.
Write a script that computes the height of a projectile at any given time.
(b)
Define the model parameters. Use an initial height of \(1.5\) meters and an initial velocity of \(12\) m/s.
Solution.
% Selected Values
h0 = 1.5;
v0 = 12;
g  = 9.81;
(c)
Compute the height h at time t = 0.8.
Solution.
% Computation (height formula)
t = 0.8;
h = h0 + v0*t - 0.5*g*t^2;
(d)
Compute the time of maximum height \(t_\text{peak}\) and the maximum height \(h(t_\text{peak})\text{.}\)
Recall that the peak occurs when the velocity is zero, i.e., when \(h'(t_\text{peak}) = 0\text{.}\) Do the calculus to find the formula for \(t_\text{peak}\text{.}\)
Solution.
% compute tPeak and h(tPeak)
tPeak = v0/g;
hMax  = h0 + v0*tPeak - 0.5*g*tPeak^2;
(e)
Print a report showing t, h, tPeak, and hMax (2-decimal places).
Solution.
% Display Results
fprintf('Projectile report\n');
fprintf('At t = %.2f s, height h = %.2f m\n', t, h);
fprintf('Peak occurs at t = %.2f s, max height = %.2f m\n', tPeak, hMax);
Running this should display the following in the Command Window:
Projectile report
At t = 0.80 s, height h = 7.96 m
Peak occurs at t = 1.22 s, max height = 8.84 m
(f)
Rerun your script with (i) t = 0 and (ii) t = tPeak.
Solution.
Part (i) should display:
Projectile report
At t = 0.00 s, height h = 1.50 m
Peak occurs at t = 1.22 s, max height = 8.84 m
Part (ii) should display:
Projectile report
At t = 1.22 s, height h = 8.84 m
Peak occurs at t = 1.22 s, max height = 8.84 m

4. Piggy Bank Script.

Create a script that performs the following tasks.
(a)
Create a new script. At the very top, add clc and clear so each run starts with a clean state.
Solution.
Add the following lines to the top of your script:
% (a) Add clc and clear
clc;    % Clear the Command Window
clear;  % Clear the workspace
(b)
Suppose your piggy bank has the following number of coins:
Inside the script, define a variable for the quantity of each type of coin.
Solution.
Add the following lines to your script:
% (b) Inputs: quantity of each type of coin
nPennies  = 87;
nNickels  = 113;
nDimes    = 13;
nQuarters = 233;
(c)
In the same script, compute the worth (in cents) of each type of coin, and then compute the total value of all the coins.
Solution.
Add the following lines to your script:
% (c) Computations: values in cents
pValue = nPennies;          % 1 cent each
nValue = 5  * nNickels;
dValue = 10 * nDimes;
qValue = 25 * nQuarters;

totalCents = pValue + nValue + dValue + qValue;
(d)
Display the total value of all the coins using the fprintf command.
Solution.
Add the following lines to your script:
% (d) Display the total value in cents
fprintf('Total value (in cents): %i cents\n', totalCents);
(e)
Save the script as piggy_bank_counter.m. Run the script to test it and see the output.
Solution.
The output in the Command Window should be:
Total value (in cents): 6607 cents
(f)
Finally, compute
and run the script again to display these values.
Hint: After getting the total value in dollars, use MATLAB’s floor function to round the dollar amount down to the nearest whole number to get the number of dollars.
Solution.
Add the following lines to your script:
% (f) Convert to dollars and print the dollars and cents
totalDollars = totalCents/100;
nDollars = floor(totalDollars);
nCents = totalCents - nDollars * 100;
fprintf('Total value (in dollars): %i dollars and %i cents\n', nDollars, nCents);
The output in the Command Window should be:
Total value (in dollars): 66 dollars and 7 cents

5. Solving a Quadratic Equation.

The solution to the quadratic equation of the form:
\begin{equation*} a x^2 + b x + c = 0 \end{equation*}
is given by the quadratic formula:
\begin{equation*} x = \frac{-b \pm \sqrt{b^2 - 4 a c}}{2 a}\text{.} \end{equation*}
An important part of this formula is the value under the square root, called the discriminant, given by:
\begin{equation*} \Delta = b^2 - 4 a c\text{.} \end{equation*}
Knowing the discriminant tells you the nature of the solutions:
  • If \(\Delta\) is positive, there are two distinct real solutions.
  • If \(\Delta\) is zero, there is exactly one real (repeated) solution.
  • If \(\Delta\) is negative, the solutions are complex numbers.
For example, the equation \(x^2 + x - 6 = 0\) has
  • coefficients \(a = 1\text{,}\) \(b = 1\text{,}\) and \(c = -6\text{,}\) and
  • discriminant \(\Delta = 1^2 - 4(1)(-6) = 25\text{,}\) which is positive.
So there are two distinct real solutions given by:
\begin{align*} x_1 \amp = \frac{-1 + \sqrt{1^2 - 4(1)(-6)}}{2(1)} = \frac{-1 + \sqrt{25}}{2} = 2, \quad \text{and}\\ x_2 \amp = \frac{-1 - \sqrt{1^2 - 4(1)(-6)}}{2(1)} = \frac{-1 - \sqrt{25}}{2} = -3\text{.} \end{align*}
Write a script that uses the quadratic formula to solve a quadratic equation.
(a)
Create a new script file and add the following to the top:
% This script uses the quadratic formula to solve an equation of the form:
%
%    a*x^2 + b*x + c = 0
%
% where a, b, and c are given.

clc; clear;
This ensures each run starts from a clean state.
Solution.
Add the following lines to the top of your script:
% (a) Add clc and clear
clc;    % Clear the Command Window
clear;  % Clear the workspace
(b)
Define variables a, b, and c in your script to represent the coefficients of any possible quadratic equation.
As a starting point, use the values in the example above.
Solution.
Add the following lines to your script:
% (b) Set a, b, and c  (example: x^2 + x - 6 = 0)
a = 1;
b = 1;
c = -6;
(c)
Using these variables, compute
  • the discriminant and
  • the solutions to the quadratic equation.
Solution.
Add the following lines to your script:
% (c) Compute the discriminant and the two solutions
discriminant = b^2 - 4*a*c;
x1 = (-b + sqrt(discriminant)) / (2*a);
x2 = (-b - sqrt(discriminant)) / (2*a);
(d)
Display the two solutions using fprintf and disp (for the solutions).
Solution.
Add the following lines to your script:
% (d) Print a short report
fprintf('\n');
fprintf('Solving the equation:\n');
fprintf('    %g x^2 + %g x + %g = 0\n\n', a, b, c);

fprintf('Discriminant: %g\n', discriminant);
fprintf('Solutions:\n');
fprintf('    x1 = ');
disp(x1);
fprintf('    x2 = ');
disp(x2);
(e)
Save the script as quadratic_solver.m and run it to make sure it works.
Solution.
The output in the Command Window should be:
Solutions: 
x1 =		2

x2 =		-3
(f)
Change the values of a, b, and c to solve the equation
\begin{equation*} 2 x^2 - 4 x - 6 = 0\text{.} \end{equation*}
Run the script again to see the new solutions.
Solution.
Update the coefficient definitions in your script as follows:
% (f) Update coefficients for new equation
a = 2;
b = -4;
c = -6;
The output in the Command Window should be:
Solutions: 
x1 =		3

x2 =		-1
(g)
Change the values of a, b, and c to solve the equation
\begin{equation*} x^2 + 2x + 5 = 0\text{.} \end{equation*}
Run the script again to see the new solutions.
Solution.
Update the coefficient definitions in your script as follows:
% (g) Update coefficients for new equation
a = 1;
b = 2;
c = 5;
The output in the Command Window should be:
Solutions: 
x1 =	-1.0000 + 2.0000i

x2 =	-1.0000 - 2.0000i
(h)
The previous example shows that our script can handle complex solutions.
Are there any quadratic equations that our script cannot handle? If so, give an example and explain why the script fails.
Solution.
The script fails when a = 0, because the quadratic formula divides by \(2a\text{.}\) For example, the equation
\begin{equation*} 2x + 5 = 0 \end{equation*}
corresponds to a = 0, and then the expressions (2*a) in the denominator become zero.
A more robust solver would first check whether a is zero, and if so, switch to solving a linear equation. Making that kind of decision requires flow control, which we will study later.

Exercises πŸ€”πŸ’­ Conceptual Questions

1. Script Concepts.

(a) Running a Script.
When you run a MATLAB script, MATLAB executes commands:
  • in a random order based on variable names
  • from top to bottom in the order they appear
  • from bottom to top
  • only on lines that end with semicolons
(b) Workspace Connection.
    A script runs in its own private workspace, separate from the Command Window.
  • True.

  • Scripts share the base workspace with the Command Window, so variables can persist between runs unless you clear them.
  • False.

  • Scripts share the base workspace with the Command Window, so variables can persist between runs unless you clear them.
(c) Semicolons.
    Ending a line with a semicolon prevents that line’s result from automatically printing in the Command Window.
  • True.

  • Semicolons prevent intermediate computations from cluttering the output, making the final results easier to read.
  • False.

  • Semicolons prevent intermediate computations from cluttering the output, making the final results easier to read.
(d) Finding a Script.
If MATLAB says it cannot find your script, the most likely issue is that:
  • The script is not in the Current Folder
  • You forgot to use clc at the top
  • You used fprintf instead of display
  • Your script contains comments
(e) Match the Commands.
(f)