MATLAB Scripts

Grady Wright
Department of Mathematics
Boise State University

Goal

The purpose of this note is to give a basic introduction to writing MATLAB "scripts", which provides a basic means of writing programs. 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. 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 (by default the MATLAB editor will do this when you save the file for the first time). Otherwise MATLAB will 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 on a Windows machine, or option-command-r on a Mac.
    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

Variables

As discussed in the introductory tutorials, there is no need to declare variable types anywhere in your script. 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 may consider adding clear all and close all at the beginning of your script to erase any values that may have previously been stored in these variables.

Output

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:

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

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

Repetitive operations (for 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
commands
end

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 2:
clear
n = 20; x = zeros(n,1);
x(1) = 1;
x(2) = 1;
for i=3:n
   x(i)= x(i-1) + x(i-2);
end
semilogy(1:n,x,'xb-');
xlabel('n'), ylabel('nth Fibonacci number');

In the following example we see a so-called nested for-loop to fill in entries of a table according to some arithmetic pattern. 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 3:
clear
for i=1:5
    for j=1:5
       A(i,j)=10*i+j;
    end
end
A

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 4:
clear
N = 10;
mysum = 0;
for k=0:N
    mysum = mysum+1/factorial(k);
end

e_approximation = mysum
e_exact = exp(1)

Now let's use a nested sum to approximate the value of $\exp(x)$ for $0\leq x \leq 7$ using 10 terms in the Taylor series of $\exp(x)$. We also plot the approximation as a function of $x$. Here we will include comments in the code using the percent sign (%). Any text following (%) on the same line will not be interpreted by MATLAB. This allows one to add comments which helps others understand what your code is suppose to do. Commenting your code is essential when writing programs.

Example 5:

clear
N = 10;

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

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

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

semilogy(x,e)
title('Approximation of e^x for x between 0 and 7')
xlabel('x')
ylabel('e^x')

Exercise 1.
Rewrite the above program so that it uses linspace to create the array x and only one loop to compute the approximations at all values in x. This will require the use of vectorization and using the . operator.

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.