Basics of MATLAB
Basics of MATLAB
1 Introduction
The purpose of this lab is to familiarize yourself with basic MATLAB functionality. MAT-
LAB is a computational tool consisting essentially of a command interpreter/compiler for
which there is a vast set of libraries and graphical representation tools, in addition to a nice
user interface. Because of its simplicity and ease of use it is widely used in industrial and
academic environments.
In this lab you will focus on several easy tasks that will make you feel comfortable with MAT-
LAB’s development environment and programming language. A more comprehensive intro-
duction/tutorial can be obtained for free from Mathworks, the makers of MATLAB http://
www.mathworks.com/access/helpdesk/help/techdoc/matlab.shtml (in documentation choose
Getting Started ). After gaining some experience you’ll rarely need any tutorials or books,
since the available help command and the ability of searching the electronic documentation
is satisfactory for most problems.
MATLAB in its early versions started as a simple interactive UNIX shell in which users could
execute mathematical operations. In its most current versions, MATLAB includes a highly
configurable Integrated Development Environment (IDE) which facilitates writing, testing,
debugging and even optimizing the calculations we need to perform. We can run MATLAB
in UNIX by typing:
matlab
at the shell’s command prompt. A graphical interface with 3 main windows appears. The
Command Window with the command prompt >> is where we execute our code. The Launch
Pad window provides easy access to tools, demos, and documentation while the Command
History window displays the commands we have recently typed. History is very useful since
by simple scrolling we can look at our work several days back, an electronic form of lab
notebook. Under the View menu we can find all the windows that can be displayed. We
can open any those windows and selectively float, dock or even tab list them inside the IDE.
Any changes we make to the IDE will be saved when we quit MATLAB by typing:
1
>> quit
at MATLAB’s prompt or by selecting Exit under the File menu. One last thing to note is
that if we don’t need the IDE we can run MATLAB using the command:
MATLAB encapsulates most of its functionality in system- or user-defined text files that
contain commands. Those files (like lpc.m in the previous section) are called m-files. In
order for MATLAB to be able to find those files they need be in the so-called path. Since we
will be writing some basic functions for this lab series it is wise to create a directory structure
and organize our code for future reference. This is a good practice for all the courses that
require MATLAB programming.
To Do 1
Create a directory structure and set the path.
First we make sure we are in our home directory by typing:
>> cd ~;
Now we have a complete directory structure were we can store our work for this class.
Moreover we created a file called startup.m in the matlab directory which has a special
2
functionality (using an exclamation mark invokes an operating system command). This file
is automatically called by MATLAB at launch. This is the best place were we can set our
path so that MATLAB can find the m-files we will write.
Edit startup.m by typing:
>> cd ~/matlab;
>> edit startup;
We can see how our IDE configuration helps us. startup.m is opened by the editor in a tab
right next to lpc.m and prony.m m-files something that facilitates editing since we can be
testing code in the Command Window and copy-paste it in the editor. Next in startup.m
we type the following commands:
disp(’This startup.m file has been modified for the E3084 lab’);
addpath(’~/matlab/elen_e3084/’);
addpath(’~/matlab/elen_e3084/lab1’);
addpath(’~/matlab/elen_e3084/lab2’);
addpath(’~/matlab/elen_e3084/lab3’);
addpath(’~/matlab/elen_e3084/lab4’);
addpath(’~/matlab/elen_e3084/lab5’);
addpath(’~/matlab/elen_e3084/lab6’);
addpath(’~/matlab/elen_e3084/lab6’);
>> startup;
at the command prompt executes the file we just saved and the directories we created are
now in the path and thus searchable by MATLAB. We essentially created our first m-file.
Show the TA the startup.m file.
Finally we will now start a diary function that will capture all our commands from now on.
Go to the lab1 directory using the cd command the same way as in UNIX. Then type:
All the commands you type will be collected by the diary function. You should show this to
the TA or lab assistants at the end of the lab, so that they can assess that you have done
during the lab.
3
3 Basic of MATLAB
Whenever you are unsure of the syntax of a command, or want to find how to do some-
thing you can rely on a few helpful commands that can quickly provided with the needed
information. The most basic command we will use is help. Typing:
"HELP TOPIC" gives help on the specified topic. The topic can be a
command name, a directory name, or a MATLABPATH relative partial
pathname (see HELP PARTIALPATH). If it is a command name, HELP
displays information on that command. If it is a directory name,
HELP displays the Table-Of-Contents for the specified directory.
For example, "help general" and "help matlab/general" both list
the Table-Of-Contents for the directory toolbox/matlab/general.
LOOKFOR XYZ looks for the string XYZ in the first comment line
of the HELP text in all M-files found on the MATLABPATH. For all
files in which a match occurs, LOOKFOR displays the matching lines.
4
For example, to learn more about the function sum you should type help sum. This is the
general style of help. It not only gives a detailed description of the topic often including
examples, but refers to related topics as well. For example, when seeking help about the
function sum you also learn that there is a function prod that is somewhat related.
This style of help is displayed on the prompt. As you probably noticed the screen is cluttered
with text and we need to scroll up in order to read the full article. An arguably better way
to get help is to use the HTML version. The command doc works the same way as help with
the difference that it launches a window displaying the HTML version of the help file. This
way is preferable as links to related commands as well as graphics are included. Typing:
gives us the HTML version. Typing help without arguments gives us a full list of topics and
toolboxes with short descriptions.
3.2 Variables
As we have seen in previous sections we can type commands and execute them in the com-
mand prompt >>. Now if we type:
>> x = 5
x =
5
we define a variable x and assign the value 5. Notice that we don’t need to define the type
(such as string or number) of the variable. MATLAB is able to infer the type (within reason).
So now when we type:
>> x
x =
5
we get the value that we previously assigned. Notice that the variable along with its type
and size appear on the Workspace window that we previously docked on the main MATLAB
IDE.
Any string starting with a letter can be a variable such as m, a, test, TEST etc. Strings
starting with other characters such as 1alfa, -a or a+ cannot be variables. For example,
when we type 1alfa the error message:
5
>> 1alpha = 5
??? 1alpha = 5
|
Error: Missing operator, comma, or semicolon.
appears. It is important to note that variable names are case sensitive which means that
a and A are two different variables (carelessness about this is frequently a source of bugs in
large pieces of code).
When we type a command, operation or a variable name, its value appears on the screen.
Sometimes this is inconvenient (e.g., if you write a script or program you don’t want to
display the output at every step). The display of the value can be suppressed by putting
a semicolon after the command or a variable name. In general it is preferable to add the
semicolon especially when we define variables so that we don’t clutter the command prompt.
For example we could have defined the previous variable x by typing:
>> x = 5;
The command:
>> clear x;
clears the variable from the workspace. This is useful for example when we want to reclaim
system memory. We can also clear variables when we want to make sure that any old values
are not going to be used by accident.
MATLAB includes a number of special variables that are built in the system. For example,
entering pi gives us the value of π.
>> pi
ans =
3.1416
6
Other special variables include i and j, that, as you guessed, correspond to the imaginary
unit. It is possible to overwrite special variables. For example, typing pi = 5 assigns a new
value, thus loosing its previous, built-in value. The original values of the built-in variables
can be returned by using the clear statement as illustrated below:
>> pi = 1
pi =
1
>> i = 2
i =
2
>> j = 3
j =
3
>> ans = 4
ans =
4
>> clear pi i j ans
>> pi
ans =
3.1416
>> i
ans =
0 + 1.0000i
>> j
ans =
0 + 1.0000i
>> ans
ans =
0 + 1.0000i
Note also that a variable ans is created and updated whenever there is an output to the
screen. This variable (short for answer) is an auxiliary variable and although you can change
its value it will be rewritten whenever you have any output to the screen.
MATLAB internally uses 8-byte floating point numbers to store arithmetic variables. This
can be verified by looking at the Workspace window under the column Bytes. However,
entering or displaying numbers is subject to formatting for presentation purposes. For ex-
ample:
7
>> 0.000000000000001
ans =
1.0000e-015
In order for this long decimal number to be displayed better, MATLAB uses mantissa-
exponent notation. In fact the exponent can be separated with either e or E. We can also
use this formating as an input method:
>> 1.000000e-14
ans =
1.0000e-014
>> 1.00E-14
ans =
1.0000e-014
>> 1E-14
ans =
1.0000e-014
It should be emphasized at this point that the way numbers are displayed does not affect
the internal accuracy with which they are stored or manipulated internally by MATLAB. In
fact we can increase the accuracy by which variables are displayed by typing:
>> 1.000000e-14
ans =
1.000000000000000e-014
>> 1.00E-14
ans =
1.000000000000000e-014
>> 1E-14
ans =
1.000000000000000e-014
For a complete description you can get help by typing: help format. We can return to the
default formating by typing:
Finally, it is worth noting that MATLAB displays integers whenever possible. For example:
8
>> 3.0 * 2
ans =
6
>> 6 / 3.0
ans =
2
This is a nice example of how MATLAB is able to infer the type of the variable.
MATLAB’s simplest mathematical objects are scalars, vectors and matrices. These are the
quantities you are going to manipulate more often, as vectors and matrices can be used to
represent signals, images, among other things. The command interpreter is highly optimized
to perform operations with vectorial quantities. This is in fact what the name MATrix
LABratory denotes. In this lab session you will get a first contact with these objects, and
will learn more in subsequent lab sessions.
There are two types of vectors. Row vectors and column vectors. By convention one typically
uses column vectors to represent signals. For displaying purposes we will use row vectors
since they occupy less lines when printed. The simplest way to create a column vector is by
the bracket concatenation operator. We separate the various values by using a semi-colon.
Typing:
gives
x =
1.0000
-12.3000
3.1416
1.4142
If we want to create a row vector instead we can use spaces or commas as separators instead:
or
9
give
x =
We can switch from row to column representation easily by using the transpose operator
{.’}. For example:
>> x.’
ans =
1.0000
-12.3000
3.1416
1.4142
Note that if you omit the dot in the transpose operator there is also a conjugation operation
being performed (this is call the Hermitian transpose). Type x’ and comment on the result.
In the next lab we will learn more about vectors, and see how these can be used to create
signals.
3.2.7 Strings
Vectors don’t need to consist of numerical values. In fact we can think of vectors of characters,
which constitute a string. for simplicity MATLAB allows us to manipulate these objects in
a very convenient way. Characters enclosed in single quotes (apostrophes) are defined as
strings. In the simplest case strings can be used for displaying messages:
10
This use of square brackets is essentially a way to create vectors as we seen before (we will
see later how to use this in more general settings. The important thing here is that strings
inside the square bracket have to be separated by spaces or commas.
Numbers and numerical variables can be converted into strings by using the num2str func-
tion. The general form is num2str(x,n) where x is the numerical variable and the integer n
denotes the maximum digits of precision. For example:
>> x = sqrt(2);
>> num2str(x,3)
ans =
1.41
>> num2str(x,12)
ans =
1.41421356237
As discussed variables can be displayed by entering the variable without semicolon. A more
flexible, and generally more favored way of displaying variables is to use the disp(var)
command where var stands for an arbitrary variable. For example:
>> x = 3;
>> disp(x)
3
Finally, combined messages can be created by converting numerical variables into strings
and concatenate them with the string variables containing the message. For example:
3.3 Operators
One can see MATLAB as a glorified calculator. In this sense operators are the special
characters that provide MATLAB the calculator functionality. The most basic operators
are:
11
Arithmetic operators.
plus - Plus +
uplus - Unary plus +
minus - Minus -
uminus - Unary minus -
mtimes - Matrix multiply *
times - Array multiply .*
mpower - Matrix power ^
power - Array power .^
mldivide - Backslash or left matrix divide \
mrdivide - Slash or right matrix divide /
ldivide - Left array divide .\
rdivide - Right array divide ./
kron - Kronecker tensor product kron
Relational operators.
eq - Equal ==
ne - Not equal ~=
lt - Less than <
gt - Greater than >
le - Less than or equal <=
ge - Greater than or equal >=
Logical operators.
Short-circuit logical AND &&
Short-circuit logical OR ||
and - Element-wise logical AND &
or - Element-wise logical OR |
not - Logical NOT ~
xor - Logical EXCLUSIVE OR
any - True if any element of vector is nonzero
all - True if all elements of vector are nonzero
Bitwise operators.
bitand - Bit-wise AND.
bitcmp - Complement bits.
bitor - Bit-wise OR.
bitmax - Maximum floating point integer.
bitxor - Bit-wise XOR.
bitset - Set bit.
bitget - Get bit.
bitshift - Bit-wise shift.
12
Set operators.
union - Set union.
unique - Set unique.
intersect - Set intersection.
setdiff - Set difference.
setxor - Set exclusive-or.
ismember - True for set member.
The use of most operators is self explanatory but if you need more help in any of them you
can use the help system, e.g. help mtimes gives:
* Matrix multiply.
X*Y is the matrix product of X and Y. Any scalar (a 1-by-1 matrix)
may multiply anything. Otherwise, the number of columns of X must
equal the number of rows of Y.
>> a = 5;
>> b = 3;
>> a + b
ans =
8
>> 2 ^ 4
ans =
16
>> 1 | 0
ans =
1
The elementary functions can be found by typing help elfun. The most basic functions
follow.
13
Trigonometric.
sin - Sine.
sinh - Hyperbolic sine.
asin - Inverse sine.
asinh - Inverse hyperbolic sine.
cos - Cosine.
cosh - Hyperbolic cosine.
acos - Inverse cosine.
acosh - Inverse hyperbolic cosine.
tan - Tangent.
tanh - Hyperbolic tangent.
atan - Inverse tangent.
atan2 - Four quadrant inverse tangent.
atanh - Inverse hyperbolic tangent.
sec - Secant.
sech - Hyperbolic secant.
asec - Inverse secant.
asech - Inverse hyperbolic secant.
csc - Cosecant.
csch - Hyperbolic cosecant.
acsc - Inverse cosecant.
acsch - Inverse hyperbolic cosecant.
cot - Cotangent.
coth - Hyperbolic cotangent.
acot - Inverse cotangent.
acoth - Inverse hyperbolic cotangent.
Exponential.
exp - Exponential.
log - Natural logarithm.
log10 - Common (base 10) logarithm.
log2 - Base 2 logarithm and dissect floating point number.
pow2 - Base 2 power and scale floating point number.
realpow - Power that will error out on complex result.
reallog - Natural logarithm of real number.
realsqrt - Square root of number greater than or equal to zero.
sqrt - Square root.
nextpow2 - Next higher power of 2.
Complex.
abs - Absolute value.
angle - Phase angle.
14
complex - Construct complex data from real and imaginary parts.
conj - Complex conjugate.
imag - Complex imaginary part.
real - Complex real part.
unwrap - Unwrap phase angle.
isreal - True for real array.
cplxpair - Sort numbers into complex conjugate pairs.
Remember to use the help command to get more information for any of those functions.
EXP Exponential.
EXP(X) is the exponential of the elements of X, e to the X.
For complex Z=X+i*Y, EXP(Z) = EXP(X)*(COS(Y)+i*SIN(Y)).
>> exp(1)
ans =
2.7183
>> sin(pi/2)
ans =
1
>> asin(1)
ans =
1.5708
15
3.5 Flow control
Repeating statements for an arbitrary number of times is one of the most important features
of most programming languages. It used to be the case that MATLAB was not able to repeat
statements efficiently but this is not true anymore. Starting with version 6.5 MATLAB
includes a JIT-compiler which is responsible for optimizing loops.
The for loop repeats a group of statements for a fixed, predetermined number of times. A
matching end denotes the end of the loop. For example:
The semicolon terminating the inner statement suppresses repeated printing, and the s after
the loop displays the final result. Nested loops are good to be indented for readability. The
MATLAB editor smart-indents nested loops and other constructs as we type. For example
indentation makes the following loop more readable.
for I = 1:M
for J = 1:N
Q(I,J) = (I+J)^2;
end
end
The if statement executes a group of commands depending on the value of a logical expres-
sion. The else and elseif constructs are optional and provide additional branching. For
example:
>> x = 3;
>> if x < 0
disp(’negative’);
else
disp(’non-negative’);
end
16
non-negative
>>
Using the command prompt is definitely recommended for temporary calculations however
it is fundamental to be able to save code so that we can run it again in future MATLAB
sessions. The saved MATLAB files are called m-files and must have an extension .m. We
have already created our first m-file, startup.m in a previous section.
One can edit m-files using any text editor, such as EMACS but we recommend using the
editor provided with the IDE. As we start working with m-files we will appreciate the cus-
tomized IDE we have already created. You can imagine that testing code interactively on the
command prompt and then copy-paste it to the editor right next to the command prompt
is a very efficient way to work. You can edit .m files using the command edit:
should open the editor window and display the code for the function lpc.m.
will open another tab in the editor with the file prony.m. Before executing a script you must
not forget to save all the changes.
All the constructs we have learned so far are valid in an m-file. In addition we can now have
comments in our code which definitely help for future reference. There is nothing worse than
reading your own code 2 months after we wrote it only to realize that you don’t remember
what you wanted to calculate!!! Lines that start with % are treated as comments.
It is important to state that there are two types of m-files. Scripts and functions. Quoting
from MATLAB help.
• Scripts do not accept input arguments or return output arguments. They operate on
data in the workspace.
• Functions can accept input arguments and return output arguments. Internal variables
are local to the function.
It is preferable to think and organize our code in terms of functions. Scripts might seem
easier to write but they are very difficult to debug as every variable they use is stored in
17
the workspace. Writing modular code using functions is a skill that you definitely should
develop as we go.
As an example assume that we need to write a function with name myfun that takes three
input arguments and returns two output arguments. Then we should have as first line the
function definition [out,N] = myfun(x,time,freq) and we should save the function in a
file with filename myfun.m. Notice that the function name is the same as the filename as
this is the only way for MATLAB to find and execute the function.
A good practice is to include comments right on the second line of the m-file. Those comments
are automatically displayed by MATLAB if we were to ask for help by typing help myfun.
We will demonstrate some meaningful help comments below.
To Do 2
Write 3 functions that calculate the factorial.
In the first function we are going to use the for loop. First check which directory you are in
by typing pwd. If you are not in the lab1 directory go there using the command cd. Create
an m-file by typing:
function y = fact_for(x)
% FACT_FOR Calculates the factorial using a for loop
% y = fact_for(x)
%
% x: a positive integer
% y: x’s factorial
% Initialize y
y = 1;
% Do the loop
for I = 1:x
y = y*I;
end
Save and verify that the function gives the right result. If we get help for this function by
typing help fact for what is displayed on the command prompt?
What do you get if you type fact for(10)?
How about fact for(1000)? In this case the result is larger than the largest number that
MATLAB can represent so it substitutes the result with infinity.
How about fact for(-10)? Is this result correct? Modify the function so that is displays
an error message when the input is less than zero.
18
Now for the second function we will use the programming concept of recursion. Recall that
the factorial can be defined recursively, as n = n×(n−1)and 0 = 1. Create a second function
fact rec.m that computes the factorial using recursion (i.e., the function should call itself).
What do you get if you type fact rec(10)?
How about fact rec(1000)? In this case we get an error which means that we cannot have
arbitrarily deep recursions.
Finally for the third function we are not going to provide the code. You should create a
function called fact whi from scratch that implements the factorial using the while con-
struct instead of for or the recursion. Since we haven’t introduced while you should get
help and see how it is used. Don’t forget to add meaningful comments similar to the ones
in the previous two functions. You should use different input/output variable names.
Show the TA all three functions.
To Do 3
Write a function primetest.m that tests if a number is prime or not. Then write a script
that displays the first 100 primes. Show the TA your code and script output.
At this point you should turn off the diary function we started in the beginning of this lab
session. You can do that by typing:
This will create the diary file that contains all the commands you typed in the command
prompt as well as all the output they generated. Show the a TA or LA your diary file.
19