MATLAB Programming I: Scripts

Grady Wright
Department of Mathematics
Boise State University


The purpose of this tutorial is to give a basic introduction to programming in MATLAB using "scripts". It requires no programming experience, but some familiarity with MATLAB is recommended. All background needed can be found on the tutorial Overview of MATLAB. Upon completing the tutorial, you should know how to

A number of examples will be given below. No output is given in the tutorial since it is expected that you implement the examples yourself and then run them in the MATLAB command window to get the output.

Disclaimer: Many of the examples and exercises given below may seem to be irrelevant and even a little stupid. However, by understanding them you will have all the background to write programs to solve all the homework problems.

Background on MATLAB scripts

How to edit and run a MATLAB script

To write scripts (or programs) in MATLAB you should use a text editor. MATLAB has an integrated text editor which is very good and is highly recommended since it provides syntax highlighting and programs can be run and debugged directly from it. To open the editor, simply select the "New Script" from the top menu bar. Alternatively, select or "Open…" option, if you want to open an existing M-file. In the editor you can now type in your MATLAB commands similar to how you input them on the command line. However, the main difference is when you press enter after typing a command, that command is not executed. Menus and short-cut keys for editing text (e.g. cut/copy/paste) are similar to many other text editors and be customized through the "Preferences" menu. In order to run a script do the following:
  1. If the script is not saved,then save it as <filename>.m, where <filename> is anything you wish to name the file. It is important to add ".m" at the end of the filename. Otherwise MATLAB may not understand it.
  2. Use one of the following techniques to run the saved script:
    1. If the script is currently displayed as the top window in the editor, hit the <F5> key.
    2. If the script is currently displayed as the top window in the editor, press the "Play" button on the toolbar with the mouse.
    3. Go to the command window and type the name of the file containing your script at the prompt and press enter. When typing the filename in the command window do not include ".m". Note that for the script to run, it must be in the current working directory or on the MATLAB path.

In case your code has errors, MATLAB will complain when you try to run the program in the command window. When this happens, MATLAB will indicate what error occurred. You should try to interpret the error message and make necessary changes to the script in the editor. The error that is reported by MATLAB is hyperlinked to the line in the file that caused the problem. Using the mouse you can thus jump right to the line in your program that has caused the error. After you have made the changes, make sure you save your file before trying to run the program again in the command window.

General programming advice

The best programming advice, which applies to even the most experienced programmers, is to never try to write all the code at once. Programming should be done in small steps with each step tested to ensure it works before proceeding to program the next step. Implementing a longer program should always start with an outline using pen and paper before one line of code is ever typed into the editor.

Basic programming structures


As discussed in the introductory tutorial, there is no need to declare variable types anywhere in your script (or functions). However, it may be necessary to initialize some variables before they are used, and it is good MATLAB programming practice to initialize vectors and matrices to their proper sizes at the beginning programs. Furthermore, to avoid simple bugs that can be very difficult to find, you should use the clear at the beginning of your script (but not function) to erase any values that may have previously been stored in these variables.


To make MATLAB give an output, such as return the value of a variable, you type the name of the variable without any semi-colon (;) following the variable. In many cases, there is no need to see the value of a variable every single time MATLAB uses it. If MATLAB re-computes the value of a variable 1000 times, we probably don't want to see the result every single time. To suppress the output of a value, just add a semi-colon after the variable. Then MATLAB will perform the command, but will not show it on the screen.

As a first example, consider the following program that takes a temperature value in Kelvin and outputs that value in Fahrenheit and Celsius.

Example 1:

temp_kelvin = 233.15;
temp_celsius = temp_kelvin-273.15
temp_farenheit = 9/5*temp_celsius + 32

Not that values of temp_celsius and temp_farenheit are displayed in the command window since no semicolon is placed after these lines.

Logical and relational operators

Logical and relational operators are fundamental for making decisions and controlling the flow of a program. These are listed below together with their MATLAB syntax.

Logical operators
Operation: MATLAB syntax:
Logical and &
Logical or |
Negate ~

Relational operators
Operation: MATLAB syntax:
Strictly less than <
Less than or equal to <=
Strictly greater than >
Greater than or equal to >=
Equal to ==
Not equal to ~=

Each of these commands results in one of two values, a logical 1 or a logical 0. The value 1 means true, while 0 means false. The keywords true and false can also be used to represent these logical values. Note that all the logical commands apply to scalar or matrices. When matrices are used with these operators the comparison is done element-by-element.

It is important to know the difference between = and ==. The former is used when assigning a number to a variable, e.g., x=3;. The latter is used to check if two expressions are equal. The examples below illustrate this difference.

Example 2: At the command prompt type the following:

a = 5
b = 6
a == b
a ~= b
a < b
a > b
c = 4
(a < b) & (c < b)
(a < b) & (c > b)
(a < b) | (c > b)
true == true
false == false
false == true
c = 1:10
a <= c
a >= c
a = [0 1 4 5 8 3 4 9 10 2];
a <= c

Conditional statements

Often in programs we want the computer to check whether a statement is true or false and perform different operations depending on the result of this test. This can be done using a so-called if-statement. The syntax is given below.

if logical expression


if logical expression



if logical expression

elseif logical expression

Note that for each if, you need to "close" the if-statement with an end.

The use of this conditional statement is best illustrated by studying the following three examples and doing Exercise 1.

Example 3: Computing the absolute value $|x|$

x = -1;
if x < 0
    x = -1*x;

In the next example, we make MATLAB write something depending on which test our month "passes". To make MATLAB write text as output, use single quote ' around the text or try the disp function.

Example 4:

month = 3;
if month ==1 || month==3 || month ==5 || month==7 || month==10 || month==12
    num_days = 31;
elseif month == 2
    num_days = 28;
    num_days = 30;
disp(['Month ' num2str(month) ' has ' num2str(num_days) ' days'])
The last line of this example shows how to concatenate strings. For more advanced ways to do this, see the sprintf command. The last line also uses the disp function in MATLAB which offers very primitive ways of displaying text. More advanced formatting can be done with the fprintf function.

In the next example we use the command rem (remainder), which returns the remainder after the division of integer x by y. The syntax is rem(x,y).

Example 5:

number = 38;
remainder2 = rem(number,2);
remainder3 = rem(number,3);
if remainder2==0 && remainder3==0
    result = 'Your number is divisible by both 2 and 3';
elseif remainder2==0
    result = 'Your number is divisible by 2 but not by 3';
elseif remainder3==0
    result = 'Your number is divisible by 3 but not by 2';
    result = 'Your number is not divisible by 2 or 3';

Exercise 1.
Write a program similar to Example 4, which in addition to displaying how many days are in a given month, also determines the name of the month given the month number. For example, if month = 3, the text that should be output is "March has 31 days".

Repetitive operations (loops)

The power of computers is that they can repeat seemlingly mundane operations over and over (without getting bored!). An operation that is performed repeatedly is called a repetitive operation or, more common, a loop. There are different kinds of loops but the most common one in MATLAB is the for-loop. The syntax for a for-loop is:

for loop_variable = start_value : end_value

This loop will initiate loop_variable as start_value, increment loop_variable by 1 each step until end_value is reached. Below follows a few examples of how to use for-loops.

This example fills a vector with the first 20 Fibonacci numbers and then plots the results using a logarithmic scale for the dependent variable (y-axis).

Example 6:
n = 20; x = zeros(n,1);
x(1) = 1;
x(2) = 1;
for i=3:n
   x(i)= x(i-1) + x(i-2);
xlabel('n'), ylabel('nth Fibonacci number');

In the following example we see a so-called nested for-loop. This is nothing else then a "loop within a loop". Note how we must "close" each for with an end. Make sure you understand how this example works!

Example 7:
for i=1:5
    for j=1:5

In the following example, make sure you understand the purpose of the variable mysum. This is a common way of performing summations when programming.

Example 8:
N = 10;
mysum = 0;
for k=0:N
    mysum = mysum+1/factorial(k);

e_approximation = mysum
e_exact = exp(1)

In the next example, notice how we have to "shift" the indexing of the vector. MATLAB must have positive integers for indexing a matrix or vector! One of the most common mistakes when programming in MATLAB is that your program begins indexing at zero instead of one. Also note how by typing a percent sign (%) before text in the code, MATLAB does not interpret this text as code. It just serves as a comment for any person using the code. Commenting your code is essential when writing programs.

Example 9:

N = 10;

for k=0:70
x(k+1)=0.1*k; % Indices of vectors must be NON-ZERO!
mysum = 0;

for m=0:10
mysum = mysum +(x(k+1)^m)/factorial(m); % Approx exp(x) using its Taylor series

e(k+1) = mysum; % e(k+1) contains the Taylor series approx. for x=x(k+1);

title('Approximation of e^x for x between 0 and 7')

A for-loop can be terminated prematurely by using the break command. This is typically used in combination with a logical operation in an if-else block.

Exercise 2.
Write a program that approximates PI by computing the sum $$\pi = 4 \sum_{k=0}^{m} \frac{(-1)^k}{2k+1}$$. The more terms you keep in the summation, the more accurate your answer will be. (In fact, the series converges to PI as m goes to infinity.) See how many terms you need to approximate PI with 5 decimals. (Note: This is by no means the most efficient way to approximate PI, but the formula is quite spectacular considering it only involves rational numbers...)

Exercise 3.
Use the sum given in Exercise 2 to approximate PI using 10, 100, 1000, 10000 and 100000 terms. For each of these number, compute the error of the approximation. Plot the error as a function of the number of terms used in the sum.

The other type of looping mechanism used in MATLAB is the while-loop. The syntax is as follows:

while logical expression

This type of loop is commonly used in iterative methods. The body of the loop should contain code that updates the logical expression so that it eventually evaluates to true. These types of loops can result in infinite operations if one is not careful. If this happens you can terminate the operation by pressing -C on your keyboard. Here is an example of a while loop:

Example 10:

err = inf;
k = 0;
mysum = 0;
while err > 1e-8

mysum = mysum + 1/factorial(k);
k = k + 1;
err = abs(mysum-exp(1));

disp(['It requires ' num2str(k) ' in the above series to approximate e to 1e-8']);