# MATLAB Overview

Department of Mathematics
Boise State University

### Goal

The purpose of this tutorial is to give a brief overview to MATLAB. Upon completing the tutorial, you should know how to

• Start MATLAB.

• Use the elementary functions in MATLAB.

• Use variables for storing and reusing information.

• Create vectors (arrays) and matrices (two dimensional arrays).

• Use the plot functions to create simple two dimensional plots.

If you have used MATLAB before, you may wish to go quickly through this tutorial.

### What is MATLAB?

MATLAB is the most dominant commercial computing environment and is used extensively in industry for computing, analysis, and visualization. MATLAB stands for MATrix LABoratory and the software is built up around doing operations on vectors and matrices. MATLAB is not only useful for linear algebra, but it is also a great tool for analyzing data, optimization, signal and image processing, numerical integration, and numerically solving differential equations. MATLAB has very powerful graphics tools and can produce nice pictures in both two and three dimensions. Finally, MATLAB is also a programming language, and is one of the easiest programming languages for rapidly implementing algorithms for scientifically oriented applications.

### Starting MATLAB

Linux: Open a terminal and type matlab at the command prompt.

PC: Look for MATLAB under the programs menu

Mac: Click on the icon for MATLAB located on the dock.

You can quit MATLAB by typing exit or quit in the command window.

### The MATLAB environment

Note: From now on an instruction to press a certain key will be denoted by < >, e.g., pressing the enter key will be denoted as <enter>. Commands that should be typed at the MATLAB prompt, will be written in courier font.

The MATLAB environment (on most computer systems) consists of menus, buttons and a writing area similar to an ordinary word processor. There are plenty of help functions that you are encouraged to use. The writing area that you will see when you start MATLAB, is called the command window. In this window you give the commands to MATLAB. For example, when you want to run a program you have written for MATLAB you can start the program in the command window by typing its name at the prompt and hitting enter. The command window is also useful if you just want to use MATLAB as a scientific calculator or as a graphing tool. If you write longer programs, you will find it more convenient to write the program code in a separate window, and then run it in the command window (we discuss this process in the Intro to programming tutorial). MATLAB provides a very nice editor for writing code, and this editor is recommended for most users. However, any standard text editor can also be used (e.g. emacs or vi).

In the command window you will see a prompt that looks like >> . You type your commands immediately after this prompt. Once you have typed the command you wish MATLAB to perform, press <enter>. If you want to interrupt a command that MATLAB is running, type <ctrl> + <c>.

The commands you type in the command window are stored by MATLAB and can be viewed in the Command History window. To repeat any command you have already input, you can simply use the <up arrow> and <down arrow> at the command prompt to process through your commands until you reach the one you desire. You can also double click on the command you wish to repeat in the Command History window or drag-and-drop that command from that window to the command window.

### Recording a MATLAB session

You may occasionally find it useful to record the commands and output from one of your MATLAB sessions. This can be easily accomplished using the diary command in MATLAB. For example, to record all the commands and corresponding output from the present tutorial, you should type the following on the command line:

diary('MyMatlabIntro.txt')

This saves all the data typed in and output to the command window in the text file MyMatlabIntro.txt. You can locate this text file in the current working directory of MATLAB (see the Current Folder bar below the main menu bar). At the end of your MATLAB session type

diary off

### Useful functions and operations in MATLAB

The following table lists some useful operations, functions and constants in MATLAB.

Operation, function or constant

MATLAB
command

$+$ (addition)

+

$-$ (subtraction)

-

$*$ (multiplication)

*

$/$ (division)

/

^ (power)

^

$|x|$ (absolute value of $x$)

abs(x)

$\sqrt{x}$

sqrt(x)

$e^x$

\exp(x)

$\ln x$ (natural log)

log(x)

$\log_{10}x$ (base 10 log)

log10(x)

$\sin x$

sin(x)

$\cos x$

cos(x)

$\tan x$

tan(x)

$\cot x$

cot(x)

$\arcsin x$

asin(x)

$\arccos x$

acos(x)

$\arctan x$

atan(x)

$\text{arccot}\, x$

acot(x)

$n!$ (n factorial)

fact(n)

$e$ (2.71828...)

exp(1)

$\pi$ (3.14159265...)

pi

$i=\sqrt{-1}$   (imaginary unit)

1i or 1j

MATLAB is case sensitive. This means that MATLAB knows a difference between letters written in lower and upper case. For example, MATLAB will understand sin(pi) but will not understand Sin(pi).

### Obtaining Help on MATLAB commands

To obtain help on any of the MATLAB commands, you simply need to type

help <command>

at the command prompt. For example, to obtain help on the log function, we type at the command prompt:

help log

Try this now. You can get a complete list of "elementary" functions available in MATLAB by typing

help elfun

You may also get help about commands using the integrated help app, which can be accessed by selecting the "doc" hyperlink at the end of the help message or typing doc at the MATLAB command prompt. This is particularly useful if you want to search for commands for which you do not yet know the name or can't remember.

Note that the description MATLAB returns about the command you requested help on contains the command name in ALL CAPS. This does not mean that you use this command by typing it in ALL CAPS. In MATLAB, you almost always use all lower case letters when using a command.

### Using MATLAB as a Calculator

The easiest way to use MATLAB is as a calculator:

Example: Compute $5\sin(2.5^{3-\pi})+1/75$. In MATLAB this is done by simply typing

5*sin(2.5^(3-pi))+1/75

at the prompt. Be careful with parentheses and don't forget to type * whenever you multiply!

This example illustrates the order of precedence followed by MATLAB, which is similar to most calculators:

Precedence

Mathematical operation

First

Parentheses; the inner most parenthesis is executed first

Second

Exponentiation or raising quantities to a power

Third

Multiplication and division

Fourth

For expressions containing multiple operations, the highest-precedence ones are executed first followed by the next highest, etc. Operations with the same precedence (e.g. addition/multiplication or multiplication/division) are executed from left to right.

### Exercises

Compute the following expressions using MATLAB:

• $3\cos(\pi)$

• $1+1+1/2+1/6+1/24-e$

• $\ln (1000+2^{pi-2})$

• $3^4/2$

• $3/2^4$

• $(3/2)^4$

• $e^{i\pi}$

• The number ways to seat 11 individuals in 11 chairs. (Hint: Use factorials)

### Formatting Output

MATLAB allows the user to control how numerical results are formatted and displayed to the screen with the format command. Type help format and enter at the command prompt to list all the possible options for formatting output. The two main options that you will probably use the most are format short and format long.

At the MATLAB prompt type:

format long

(1+sqrt(5))/2-1

format short

(1+sqrt(5))/2-1

Observe how many decimal digits are displayed after each of the numerical calculations. Note that MATLAB did both of the above calculations using the same number of digits, the only difference is in how the results are displayed.

Another useful option for the format command is compact. This command suppresses empty lines and allows more information to be displayed on the screen at one time. At the MATLAB prompt type:

format compact

and repeat the set of four MATLAB commands listed immediately above. To return the display to printing the extra line feeds type the command format loose

### Variables in MATLAB

We can easily define our own variables in MATLAB. Let's say we need to use the value of $3.5\sin(2.9)$ repeatedly. Instead of typing 3.5*sin(2.9) over and over again, we can denote this variable as x by typing the following:

x=3.5*sin(2.9)

(Please try this in MATLAB.) Now type

x+1

and observe what happens. Note that we did not need to declare x as a variable that is supposed to hold a floating point number as we would need to do in most programming languages.

In many cases we want to know what variables we have declared. We can do this by typing whos. Alternatively, we can view the values by opening the "Workspace" window. This is done by selecting the Workspace option from the View menu.

If you want to erase all variables from the MATLAB memory, type

clear

To erase a specific variable, say x, type

clear x

To clear two specific variables, say x and y, type

clear x y

Variables can also be cleared by selecting them in the Workspace window and selecting the delete option.

### Suppressing output

Often, we do not want to have the result of a calculation printed-out to the command window. To suppress the output of a command, you can put a semi-colon at the end of the command. Again letting

x=3.5*sin(2.9)

y=2*x;

You should see that the result has not been displayed on the screen. Note that MATLAB still performs the command in "the background", it just doesn't display the result. If you want to see the value stored in y type

y

and observe what happens.

When the percent symbol % is typed, all text following that symbol (but before a line feed) is suppressed and not executed. The % symbol is useful for commenting your programs and examples of using it will be given later.

### Vectors and matrices (or arrays) in MATLAB

Vectors are created in MATLAB by putting the elements within [ ] brackets. For example type

x=[1 2 3 4 5 6 7 8 9 10]

The same vector can also be created by typing

x=1:10

The vector (1,1.1,1.2,1.3,1.4,1.5) can be created by typing

x=[1 1.1 1.2 1.3 1.4 1.5]

or by typing

x=1:0.1:1.5

Note the use of the of the 0.1 in the above statement. It tells MATLAB the spacing of the numbers from the beginning value of 1 to the ending value of 1.5.

Matrices can be created according to the following example. The matrix $$A=\begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{bmatrix}$$ is created by typing

A=[1 2 3 ; 4 5 6; 7 8 9]

i.e., rows are separated with semi-colons. If you want to use a specific element in a vector or a matrix, study the following example:

Example: Type

x=[10 20 30]

A=[ 1 2 3 ; 4 5 6 ; 7 8 9]

x(2)

A(3,1)

Here the second element of the vector is extracted by typing the variable and the position within parentheses. The same principle holds for matrices; the first number specifies the row of the matrix, and the second number specifies the column of the matrix.

Note that in MATLAB the first index of a vector or matrix starts at 1, not 0 as is common with other programming languages.

If the matrices or vectors (which are special cases of a matrices) are of the same dimensions then matrix addition, matrix subtraction and scalar multiplication works just like they are supposed to.

Example: Type

x=[1 2 3]

y =[4 5 6]

a=2

x+y

x-y

a*x

and observe what happens.

If you want to apply an operation such as squaring each element in a matrix you have to use a dot . before the operation you wish to apply. Type the following commands in MATLAB and observe the result:

x=1:10

x.^2

A=[1 2 3 ; 4 5 6 ; 7 8 9]

A.^2

A^2

The dot allows elementwise operations to be performed all at once.

The standard functions sin, cos, exp, etc. automatically act elementwise on a matrix or vector. Type

y=[0 1/4 1/2 3/4 1]

y=pi*y

sin(y)

and observe the result.

### How to plot with MATLAB

There are different ways of plotting in MATLAB. The following two techniques, illustrated by examples, are probably the most useful ones.

Example 1: Plot $\sin(x^2)$ on the interval $[-5,5]$. To do this, type the following:

x=-5:0.01:5;

y=sin(x.^2);

plot(x,y)

and observe what happens.

Example 2: Plot $e^{\sin(x)}$ on the interval $[-\pi,\pi]$. To do this, type the following:

x=linspace(-pi,pi,101);

y=exp(sin(x));

plot(x,y)

and observe what happens. The command linspace creates a vector of 101 equally spaced values between $-\pi$ and $\pi$ (inclusive).

Occasionally, you may need to plot values that vary quite differently in magnitude. In this case, the regular plot command fails to give us an adequate graphical picture of our data. Instead, you need a command that plots values on a log scale. MATLAB has 3 such commands: loglog, semilogx, and semilogy. Use the help command to see a description of each function. As an example of where we may want to use one of these plotting routines, consider the following example:

Example 3: Plot $x^{5/2}$ for $x = 10^{-5}$ to $10^5$. To do this, type the following:

x=logspace(-5,5,101);

y=x.^(5/2);

plot(x,y)

and observe what happens. Now type the following command:

loglog(x,y)

The command logspace is similar to linspace, however it creates a vector of 101 points logarithmically equally distributed between 10-5 and 105.

The following commands are useful when plotting:

 Graphing functions MATLAB command Label the horizontal axis. xlabel('text') Label the vertical axis. ylabel('text') Attach a title to the plot. title('text') Change the limits on the x and y axis. axis([xmin xmax ymin ymax]) "Keep plotting in the same window." hold on Turn off the "keep-plotting-in-the-same-window-command". hold off

Note that all text must be put within ' '. The last two commands (hold on and hold off) are best explained by trying them next time you plot.

### Exercises

• Make the following line plots appear on the same figure (try the hold on command):

1. A plot in blue with a 'o' marker of $\sin(2x)$ sampled at 5 equally spaced points between $[-\pi,\pi]$.
2. A plot in red with a 'x' marker of $\sin(2x)$ sampled at 9 equally spaced points between $[-\pi,\pi]$.
3. A plot in magenta with a '*' marker of $\sin(2x)$ sampled at 17 equally spaced points between $[-\pi,\pi]$.
4. A plot in black with a square marker of $\sin(2x)$ sampled at 65 equally spaced points between $[-\pi,\pi]$.
How does the plot change as the number of sample points increases.

• Attach labels to the axis of the previous plot and give a title to the graph.

• Plot $5\cos(x^2+1)$ on $[-2\pi,2\pi]$. Note that the squaring operation will require you to use the dot . in order for the squaring operation to act on each element individually. However, the addition operation (+) automatically acts on elements individually.