0% found this document useful (0 votes)
98 views16 pages

A Very Brief Introduction To Matlab: 1 The Basics

This document provides an introduction to basic MATLAB concepts including: - Performing arithmetic operations simply by typing them directly into MATLAB. - Storing the results of operations in variables that can be accessed and manipulated later. - Entering vectors and matrices by surrounding elements with brackets and separating with commas/semicolons. - Accessing elements of vectors and matrices using indexing and slicing operations. - Controlling program flow using conditional and loop statements like if/else, for, while.

Uploaded by

Krish Prasad
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
98 views16 pages

A Very Brief Introduction To Matlab: 1 The Basics

This document provides an introduction to basic MATLAB concepts including: - Performing arithmetic operations simply by typing them directly into MATLAB. - Storing the results of operations in variables that can be accessed and manipulated later. - Entering vectors and matrices by surrounding elements with brackets and separating with commas/semicolons. - Accessing elements of vectors and matrices using indexing and slicing operations. - Controlling program flow using conditional and loop statements like if/else, for, while.

Uploaded by

Krish Prasad
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

A Very Brief Introduction to Matlab

by John Walsh, for ECE 220 Fall 2004


August 23, 2004

1 The Basics
You can type normal mathematical operations into MATLAB as you would in an electronic calculator.
Begin by typing 1+2 [Enter], you should see

EDU>> 1+3

ans =

4
Your display may not include the EDU before the prompt. This just indicates that you are using a version
other than the student version of MATLAB. Other mathematical operations are just as simple as addition.
For example, here’s how to subtract two numbers

EDU>> 1-2

ans =

-1
Multiplication is naturally just as simple, as is handling non-integer numbers

EDU>> 2.25*2

ans =

4.5000
To calculate a number to an exponent use the syntax

EDU>> 2^2

ans =

4
The syntax for other binary operations implemented in MATLAB is shown in Table 1. Suppose we wish
to to store the result of an operation so we can access it later. We can do this by assigning a variable
name to the result of an operation, i.e.

1
MATLAB Expression Description
x+y Add x and y.
x-y Subtract y from x.
x*y Multiply x and y.
x/y Divide x by y.
x∧ y x to the yth power
() Parenthesis
x= y Assign the value of y to x
x == y Test to see if each elements of x and y are equal

Table 1: Arithmetic Operations in MATLAB.

EDU>> r=3*5;
EDU>> s=2.2;
EDU>> r*s

ans =

33

Here, the variable names were r and s. ”Variable names consist of a letter, followed by any number of
letters, digits, or underscores. MATLAB uses only the first 31 characters of a variable name. MATLAB is
case sensitive; it distinguishes between uppercase and lowercase letters. A and a are not the same variable.
To view the matrix assigned to any variable, simply enter the variable name.” 1 Also, you should not pick
variable names that are the same as the name of a function (to be discussed later). Notice we suppressed
MATLAB’s output for the first two commands by including a semicolon (;) at the end of the command.
Notice also that = here works differently from the usual mathematical notion of equality, instead it acts
as an assignment operator. If you want to test whether or not two items are equal, you should use ==.
MATLAB will return 1 if the two items are equal and 0 if they are not.

EDU>> s==2.2

ans =

EDU>> s==33

ans =

2 Vectors and Matrices in MATLAB


MATLAB is built to naturally work with vectors and matrices (the former are a special case of the later
with one of the two dimensions having length 1). To input a column vector into MATLAB, surround the
vector you wish to input with brackets, and separate its elements with semicolons:

1 Quote from MATLAB documentation.

2
EDU>> v=[1 ; 2 ; 3 ; 4]

v =

1
2
3
4
Row vectors are input in a similar manner, only the elements are separated by commas or spaces.

EDU>> v2=[1,2,3,4]

v2 =

1 2 3 4

EDU>> v2=[1 2 3 4]

v2 =

1 2 3 4
Note that another way to make this same vector is

EDU>> v2=[1:4]

v2 =

1 2 3 4

The second way of creating v2 exploited an operator, :, in MATLAB that counts in increments of 1 from
its left argument to its right argument. Increments other than 1 are also possible, one just uses a : x : b,
where MATLAB will produce a row vectors whose elements count in increments of x from a to b.

EDU>> v3=[1:.25:2]

v3 =

1.0000 1.2500 1.5000 1.7500 2.0000


You can concatenate two row or column vectors by using them as elements in a new row or column vector,
respectively. For a column vector, imitate the following syntax.

EDU>> v1=[1;2];
EDU>> v2=[3;4;5];
EDU>> v=[v1;v2]

v =

3
2
3
4
5

For a row vector, imitate the following syntax

EDU>> v1=[1,2];
EDU>> v2=[3,4,5];
EDU>> v=[v1,v2]

v =

1 2 3 4 5

To enter a matrix, you just combine the ideas above. Here’s an example

EDU>> A=[1,2,3;4,5,6]

A =

1 2 3
4 5 6

Note that you need to be careful that the number of rows are the same for every column, and likewise
the number of columns are the same for every row in your matrix. Otherwise, MATLAB will produce an
error.

EDU>> A=[1,2;1,2,3];
??? Error using ==> vertcat
All rows in the bracketed expression must have the same
number of columns.
As another example, imagine you tried to concatenate a row vector and a column vector

EDU>> v1=[1,2];
EDU>> v2=[3;4;5];
EDU>> v=[v1,v2];
??? Error using ==> horzcat
All matrices on a row in the bracketed expression must have the
same number of rows.

You can access elements within a matrix or vector by just specifying their coordinates. MATLAB uses 1
based indexing2 . Thus, the first element in any vector, v, is denoted by v(1).

EDU>> v=[3,4,5];
EDU>> v(1)

2 This is different from the 0 based indexing used in C, C++, JAVA and other programming languages.

4
ans =

EDU>> v(2)

ans =

EDU>> v(3)

ans =

You can also access multiple elements of a vector at a time.

EDU>> v=[1,2,3,4,5];
EDU>> v(2:4)

ans =

2 3 4

You can access elements of matrices by specifying their coordinate pairs (where the row number comes
first and the column number comes second).

EDU>> A=[1,2;3,4]

A =

1 2
3 4

EDU>> A(1,1)

ans =

EDU>> A(2,2)

ans =

EDU>> A(1,2)

ans =

5
MATLAB operations are made to naturally work with matrices. Matrix addition and subtraction can be
performed on any two matrices who have the same dimensions

EDU>> A=[1,2;3,4];
EDU>> B=[1,1;1,1];
EDU>> C=[1,2,3;4,5,6];
EDU>> A+B

ans =

2 3
4 5

EDU>> A-B

ans =

0 1
2 3

EDU>> A+C
??? Error using ==> plus
Matrix dimensions must agree.

EDU>> C-A
??? Error using ==> minus
Matrix dimensions must agree.
Matrix multiplication uses the same syntax as the multiplication of two scalars

EDU>> A=[1,2;3,4;5,6]

A =

1 2
3 4
5 6

EDU>> B=[1,3;2,4];
EDU>> A*B

ans =

5 11
11 25
17 39
Recall from linear algebra that matrix multiplication only makes sense when the number of columns
in the left matrix matches the number of rows in the right matrix. Thus, matrix multiplication is not
commutative for general matrices, and while A*B might exist, B*A might not even be defined.

EDU>> B*A
??? Error using ==> mtimes
Inner matrix dimensions must agree.

6
Occasionally, one wishes to multiply or divide two matrices of the same dimensions element by element,
this can be done using the operator .* or ./ respectively

EDU>> A=[1,2;3,4];
EDU>> B=[1,1;1,1];
EDU>> A.*B

ans =

1 2
3 4

EDU>> B./A

ans =

1.0000 0.5000
0.3333 0.2500

3 Controlling Program Flow in MATLAB: (if, for, etc)


There are eight flow control statements in MATLAB3 :

• if, together with else and elseif, executes a group of statements based on some logical condition.

• switch, together with case and otherwise, executes different groups of statements depending on the
value of some logical condition.

• while executes a group of statements an indefinite number of times, based on some logical condition.

• for executes a group of statements a fixed number of times.

• continue passes control to the next iteration of a for or while loop, skipping any remaining statements
in the body of the loop.

• break terminates execution of a for or while loop.

• try...catch changes flow control if an error is detected during execution.

• return causes execution to return to the invoking function.

All flow constructs use end to indicate the end of the flow control block. You can learn more about these
statements in MATLAB’s help system under the heading MATLABLEARNING MATLAB FLOW CON-
TROL. Get there by clicking the Help menu in the command window, then clicking on MATLAB Help,
then clicking on MATLAB, then clicking on LEARNING MATLAB , then clicking on PROGRAMMING,
then clicking on FLOW CONTROL.4

4 Using Built-in MATLAB Functions


The power of MATLAB lies in the thousands of functions that come with it. Functions can take arguments
and produce outputs. Arguments to the function are placed in parenthesis after the function name. For
example, the size function returns the dimensions of a matrix argument
3 This
section taken verbatim from the MATLAB Getting Started Documentation.
4 Theseare directions for Student Version R14. If you are using an older version, search the documentation for help on
flow control by clicking on the search tab, typing flow control, and clicking search.

7
Name Description Example
size returns the dimensions of a matrix argument size(A)
ones Creates a m n matrix whose elements are all ones ones(m,n)
zeros Creates a m n matrix whose elements are all zeros zeros(m,n)
max Find the largest element in each column of a matrix max(A)
min Find the smallest element in each column of a matrix min(A)
help Displays help about a particular command. help size

Table 2: Some MATLAB commands. Note that the help command does not place parenthesis around its
arguments.

EDU>> A=[1,2,3;4,5,6];
EDU>> size(A)

ans =

2 3

Outputs from the function can be assigned to variable names as you would assign the result of any
expression.

EDU>> z=size(A)

z =

2 3

Note that some functions will give you more information if you ask for more output arguments. For
example, the max function, which finds the largest element in a vector argument, has several options for
the number of output arguments. If there is one output argument, max just returns the maximum value
in the vector. If there are two output arguments, then max will return the maximum value in the first
output argument and the index (i.e., its location) in the second argument.

EDU>> c=[1,3,2];
EDU>> z=max(c)

z =

EDU>> [z,i]=max(c)

z =

i =

8
A few functions that you are certain to need are shown in Table 2. However, there are way to many
functions in MATLAB that you will use to list here, so in the next section we will provide you a means
for determining function names and learning how to use them. Before you start to write a program to
do something, check to see if there is a MATLAB routine that already does it by using a keyword search
in the documentation. Oftentimes you will find that there is already a program written to do what you
need, and you just need to give it the proper parameters.

5 Getting Help on Functions


One of the most important skills for a MATLAB user is the ability to find a MATLAB function that does
what you need, and then learn how to use it. To do the former, it is often helpful to do a keyword search
on the MATLAB documentation. To do this, just click on the HELP menu, and select MATLAB. Then,
in the window that pops up, click on the search tab, and enter a word or phrase that describes what you
wish to do. This often yields results more quickly than guessing function names. Once you know the
name of the function you think will do what you need, type help followed by the function name to learn
the syntax for it. For example

EDU>> help size


SIZE Size of array.
D = SIZE(X), for M-by-N matrix X, returns the two-element
row vector D = [M, N] containing the number of rows and columns
in the matrix. For N-D arrays, SIZE(X) returns a 1-by-N
vector of dimension lengths. Trailing singleton dimensions
are ignored.

[M,N] = SIZE(X) for matrix X, returns the number of rows and


columns in X as separate output variables.

[M1,M2,M3,...,MN] = SIZE(X) returns the sizes of the first N


dimensions of array X. If the number of output arguments N does
not equal NDIMS(X), then for:

N > NDIMS(X), size returns ones in the "extra" variables,


i.e., outputs NDIMS(X)+1 through N.
N < NDIMS(X), MN contains the product of the sizes of the
remaining dimensions, i.e., dimensions N+1 through
NDIMS(X).

M = SIZE(X,DIM) returns the length of the dimension specified


by the scalar DIM. For example, SIZE(X,1) returns the number
of rows.

When SIZE is applied to a Java array, the number of rows


returned is the length of the Java array and the number of columns
is always 1. When SIZE is applied to a Java array of arrays, the
result describes only the top level array in the array of arrays.

See also length, ndims, numel.

Overloaded functions or methods (ones with the same name in other directories)
help timer/size.m
help serial/size.m
help gf/size.m

9
Reference page in Help browser
doc size
In the next few sections, we will familiarize you with some of the functions necessary for using MATLAB
for ECE 220.

6 Saving and Loading Data


By now, you have probably noticed that if you assign a value to a variable name, MATLAB remembers
that value until you assign the variable name a new value, or exit the program. To see which variable
names that MATLAB is currently remembering, you can use the command who.

EDU>> clear all;


EDU>> A=.5;
EDU>> B=.3;
EDU>> who

Your variables are:

A B
A way to make MATLAB ”forget” that you have assigned that variable name a value is to use the clear
command.

EDU>> A=.5;
EDU>> A

A =

0.5000

EDU>> clear A
EDU>> A
??? Undefined function or variable ’A’.
You can clear several variable names by listing them after the clear command, or, if you want to clear
all of the variable names you can use clear all (as in the example above). Oftentimes, you will need to
save data that you have created in MATLAB to a file on your hard disk, diskette, CD, or DVD so you
can use it at a later time. This can be done using the save and load commands. The following command
saves the contents of A to a file in the current director named saveData.mat, clears the workspace, verifies
that there does not exist a variable named A anymore, then loads saveData.mat into the workspace, and
verifies that the contents of A has been restored.

EDU>> A=.5;
EDU>> A

A =

0.5000

EDU>> save saveData.mat A


EDU>> clear all
EDU>> who

10
EDU>> load saveData.mat
EDU>> who

Your variables are:

EDU>> A

A =

0.5000

Saving multiple variables is just as easy, simply list the variables that you wish to save after the filename
in the save command.

EDU>> save saveData.mat A B

If you would rather save every variable in the workspace, then do not list any variables after the save
command.

EDU>> save saveData.mat

Note that unless you give it another path, MATLAB saves the file in the current working directory. You
can determine the current directory by typing pwd. If you wish to choose another working directory, you
can use the cd command followed by the name of the directory you wish to go to. You can print the
contents of the current directory using the ls command.

7 Plotting and Labelling 2D and 3D Data


Oftentimes you will want to plot a graph using MATLAB. MATLAB’s plot command takes a vector of
data for the x axis of your graph, and a vector of y values representing the value of the function you
wish to plot at each of these points. Let’s say that you wanted to plot a single period of a sinusoid. The
following commands will produce the plot shown in Figure 1.

thetas=[-pi:pi/16:pi];
yvals=sin(thetas);
plot(thetas,yvals,b-);
xlabel(\theta);
ylabel(sin(\theta));
title(The sin Function);

The first line defines the vector of evenly spaced points in increments of π/16 between -π and π to use as
the x axis in the plot. The second line evaluates the function that we wish to plot at each of these points.
The next line plots the values of the function versus the values we chose for the x axis, and the b- demands
that the plotter connect these data points with a blue line. To learn about other options for the line style,
type help plot. The next three lines label the graph in a self explanatory way. (Note that in general, if you
wish to use a Greek letter in your plot, you can precede its English name by a backslash.) The command
axis tight will remove the extra white space on either side of your plot (try it). Note also that when we
plot a line in this manner, we need to choose the increments in the x-axis (pi/16 in this case) carefully,
so that the graph appears smooth and the essential features are visible. Oftentimes, choosing this value
is a matter of guessing and testing multiple times. Now lets suppose that you wish to plot a second line,
cos(θ), on your graph. You can do this by typing

11
The sin Function
1

0.8

0.6

0.4

0.2

sin(θ) 0

−0.2

−0.4

−0.6

−0.8

−1
−4 −3 −2 −1 0 1 2 3 4
θ

Figure 1: sin(θ) for θ ∈ [−π, π].

hold on;
plot(thetas,cos(thetas),rx-);
legend(sin(\theta),cos(\theta));
which produces the graph shown in Figure 2. The hold on command sees to it that any new lines are
drawn on top of the existing graph. If you do not use it, MATLAB will erase the previous lines and labels
on the graph. Note that we used a different plot style this time, rx-, to make it easy to distinguish between
the two graphs. Type help plot for more line styles. Finally, notice that we labelled the lines by using a
legend. Order your labels in the legend in the same order that you plotted the graphs so that the correct
label is applied to the correct line style. Note that we explored just one simple type of two dimensional
plot here. MATLAB is also capable of creating a number of other specialized 2D plots. Type help graph2d
and help specgraph for more information.
Now suppose that you want to plot a graph describing a phenomenon where there were two independent
variables instead of one. Lets imagine that you wish to plot

z = exp −(x2 + y 2 )
¡ ¢

as a function of x and y. We can do this in much the same way we created the two dimensional graph.
First we create a grid of evenly spaced points in x and y (this gives us a matrix of x values and a matrix
of y values). The command we will use to do this is called meshgrid. We then evaluate our function on
this grid and call a plotting routine. There are several plotting routines to choose between. The following
example investigates a mesh plot (Figure 3), a surface (Figure 4), and a contour plot (Figure 5). A mesh
plot is a collection of lines that look like a wire mesh that has been shaped to match a perspective of the
surface you plotted. In this instance, the color of the line also shows the height of a line. A surface plot
is similar to mesh plot, only now a perspective of the entire surface is drawn instead of just a grid. A
contour plot is a plot in which contours in x and y corresponding to a constant value of z are shown. If
you are interested in using any of these plots, be sure to read the help files for each. There are also a
number of other types of 3D plots, type graph3d to get a list of commands.

[xx,yy]=meshgrid([-1:.05:1],[-1:.05:1]);
zz=exp(-1*(xx.^2+yy.^2));

12
The sin Function
1
sin(θ)
0.8 cos(θ)

0.6

0.4

0.2

sin(θ) 0

−0.2

−0.4

−0.6

−0.8

−1
−4 −3 −2 −1 0 1 2 3 4
θ

Figure 2: cos(θ) and sin(θ) for θ ∈ [−π, π].

figure;
mesh(xx,yy,zz);
xlabel(x axis);
ylabel(y axis);
zlabel(z axis);
title(exp(-(x^2+y^2)));
figure;
surf(xx,yy,zz);
xlabel(x axis);
ylabel(y axis);
zlabel(z axis);
title(exp(-(x^2+y^2)));
figure;
[c,f]=contour(xx,yy,zz);
clabel(c,f);
xlabel(x axis);
ylabel(y axis);
title(Contours that Yield exp(-(x^2+y^2)) Constant);

8 Using .M files as scripts and functions


Instead of entering commands line by line at the MATLAB command prompt, it is often more convenient
to collect them all into a single MATLAB script. A MATLAB script is a text file filled with the MATLAB
commands that you wish to execute. To create a MATLAB script file, either use use the MATLAB editor
or your favorite text editor to type all of your MATLAB commands, save the file with a .M extension (for
example myScript.m is a valid MATLAB script file name). You can now execute all of the commands in
the file at once by typing the part of the file name before the .m (in our example this is myScript) at the
MATLAB prompt. Note that you need to be in the same directory in MATLAB as the script file that you
wish to execute (you can do this using the cd command as you would in a DOS shell). To test this out,
cut and paste the commands in the last plotting example into a text editor (e.g., the MATLAB editor),
save the file under a name with a .m extension, move MATLAB to the directory you saved it in (using
the cd command) and execute it. Do you get the plots shown in the figures? Using .M files allows you to

13
2 2
exp(−(x +y ))

0.8

0.6
z axis

0.4

0.2

0
1
0.5 1
0 0.5
0
−0.5 −0.5
y axis −1 −1
x axis

Figure 3: A mesh plot of exp(−x2 − y 2 ).

exp(−(x2+y2))

0.8

0.6
z axis

0.4

0.2

0
1
0.5 1
0 0.5
0
−0.5 −0.5
y axis −1 −1
x axis

Figure 4: A surface perspective of exp(−x2 − y 2 ).

14
2 2
Contours that Yield exp(−(x +y )) Constant
1 0.3 0.2
0.3 0.4
2 0 . 4
0.8 0. 0.5 0.5
0.6
0.6 0.7 0.6

0.
4
0.8
0.4

0.5
0.4

0.7
0.6
9

0.8
0.2 0.

0.7

0.5
0.5

0.7

0.9
y axis

0.6
0.4
0

0.6
0.8

0.4
−0.2
0.9
−0.4
0.8
0.
0.7 0.7 5
−0.6 0.
5 0.6 0.
4 0.6
−0.8 0.5 0.4
0.2 0.3
−1
0.4 0.3 0.2
−1 −0.5 0 0.5 1
x axis

Figure 5: A contour plot of exp(−x2 − y 2 ).

assemble all of your MATLAB code into one place so that it is one clear cohesive program. You should
add comments to your code (comments are text that MATLAB ignores that people reading your code can
read to help understand what your program is doing/ what you want you program to do). Comments
begin with %, anything after a % is ignored by MATLAB

EDU>> 2+2 % MATLAB will not read this

ans =

4
A commented version of the last plotting example might look like

%create an evenly spaced grid of points


[xx,yy]=meshgrid([-1:.05:1],[-1:.05:1]);
%evaluate the function to plot at these points
zz=exp(-1*(xx.^2+yy.^2));
%open a new figure window
figure;
%create a mesh plot using the data
mesh(xx,yy,zz);
%give the x axis a label
xlabel(x axis);
%give the y axis a label
ylabel(y axis);
%give the z axis a label
zlabel(z axis);
%give the graph a title
title(exp(-(x^2+y^2)));
%open a new figure window
figure;

15
%create a surface plot using the data
surf(xx,yy,zz);
%label the x-axis
xlabel(x axis);
%label the y-axis
ylabel(y axis);
%label the z-axis
zlabel(z axis);
%title the graph
title(exp(-(x^2+y^2)));
%open a new figure window
figure;
%create a contour plot using the data
[c,f]=contour(xx,yy,zz);
%label the contours according to their zz value
clabel(c,f);
%label the x axis
xlabel(x axis);
%label the y axis
ylabel(y axis);
%give the graph a title
title(Contours that Yield exp(-(x^2+y^2)) Constant);

MATLAB scripts are an efficient way of organizing code, but often one wishes to write a piece of code
that one can use time and time again, only perhaps with different parameters. To do this, one can write
their own MATLAB function file. Functions can both take and return parameters. Here is a function that
takes a parameter x and returns x2

function y=myNewFunction(x)
% This is a function that returns its argument squared.
y=x^2;

You must save functions in files whose name is the same as the function name and have the .m extension.
For our example, the file name must be myNewFunction.m. Try copying the function above into a file,
saving it, and then execute myNewFunction(2). Do you see the following?

EDU>> myNewFunction(2)

ans =

9 Where to Learn More


Now that you have completed this introduction, you should be able to get started using MATLAB in ECE
220. If you wish to become an advanced user, however, it is recommended that you read through the
”Learning MATLAB” section in the Matlab Documentation. Also, a good review of many of the ideas
presented in this laboratory can be found at http://www.mathworks.com/academia/student_center/
tutorials/intropage.html.

16

You might also like