A Brief Introduction to Matlab
MATLAB is a technical computing environment for
high-performance numeric computation and visualization. MATLAB integrates
numerical analysis, matrix computation, signal processing (via the Signal
Processing Toolbox), and graphics into an easy-to-use environment where
problems and solutions are expressed just as they are written mathematically,
without much traditional programming. The name MATLAB stands for matrix
laboratory.
We will use MATLAB in ECE 360 in order to
illustrate the concepts of digital signal processing with numerical examples.
Each homework assignment will include some optional problems that require Matlab
solutions. You will quickly realize that Matlab can often be used to check
solutions to other problems as well. This is perfectly legitimate, but you
still must turn in your analytical solutions for the pencil-and-paper problems.
MATLAB is available in DECS labs on a UNIX, PC, and
MAC platform. You can invoke MATLAB by double-clicking on the MATLAB-Icon
(MAC,PC) or by typing matlab on the Unix command line. You will then get
access to the MATLAB command line, denoted by ">>".
This document is by no means a complete reference.
There are tutorial and reference manuals for Matlab at the library.
Contents (to return to the this point in the document, simply
click on any horizontal line)
Getting
Help
Matlab is a versatile computing environment.
However, to effectively utilize this tool, you need to learn the syntax. This
document gives you the basic information you need to get started. Matlab has
excellent on-line help available. To access this help, type in the command:
>> help
and press enter. This will provide you with a list
of general areas where help is available. To get more information on this
particular topic or any specific command or function you need to know about,
type;
>> help
"topic-or-command"
For example, your favorite help command in this
class will probably soon become:
>> help
signal
For help on a specific function, such as the plot
command, type in the command or function name directly after the help command:
>> help
plot
If you have way too much time on your hands, you
can run the command:
>> demo
This will give you a graphical interface that will
let you explore the power of Matlab and show you how to do many of the
operations you will be required to do in Matlab in this course.
Elementary
Operations and Functions
Variables are assigned values by typing in a
mathematical expression, for example
![]()
would be written as:
>>
a=4*log(2)/(8^(2.3)-sqrt(23))
giving an answer of
a =
0.0242
Appending a ";" to the end of the lie
suppresses the display of the results. For example:
>>
a=4*log(2)/(8^(2.3)-sqrt(23));
will be followed by the command line. However, typing:
>> a
will display the value of the variable.
For more information on operators, consult the command
line help with:
>> help
ops
Matlab easily deals with complex numbers. To define a
complex number, use either i or j. For example:
>>
c=2+i*7;
>>
d=(1+j*3)^3;
both give complex numbers:
c = 2.0000 +
7.0000I
d = -26.0000
-18.0000i
To access the real imaginary parts of complex numbers,
use the commands real and imag. Consult command line help for
more information.
Elementary functions are evaluated element wise:
>>
x=linspace(0,10*pi,200);
>>
y=sin(x);
>> plot(y)
You can get a list of available functions with:
>> help
elfun
Matlab also provides the usual programming language
for-end, if-else-break-end, and while-end. Check out the following line for
example:
>> for
c=1:2:12; disp(c); end;
See the command line help for more information.
>> help
lang
Vectorizing
Code
Matlab provides various commands to generate vectors. A
vector can be viewed as a "sequence of samples", i.e. a digital
signal. Check out the following ones:
>> x=[ 1 2
3 4 5 ]
>> x=1:5
>> x=1:2:10
>>
x=linspace(0,1,5)
For more information on the ":"-operator type:
>> help
colon
Matlab also provides various commands to generate
matrices. Check out the following ones:
>> A=[ 1 2
3 ; 4 5 6 ; 7 8 9 ]
>>
B=eye(3)
>>
C=ones(2,3)
>>
D=diag([1 5 6 8])
>>
E=zeros(3,2)
>>
F=rand(1,5)
>>
G=randn(5,1)
The last two commands will generate random vectors, i.e.
"random signals".
The following commands are useful for matrix/vector
manipulations. One can easily take the transpose of a matrix, flip the matrix
from left to right or up and down, concatenate two matrices and so for the. Use
the matrices defined above and type:
>> P=A'
>>
P=fliplr(A)
>>
P=flipud(A)
>> Q=[ A
D]
>> R=[ A;
B]
Since Matlab generally deals with matrices you have to
be careful when using operators like "*" or "/". If you
want these operators to operate in an element-by-element fashion, you have to
denote this by a leading "."! Check out the following examples:
>> x=1:5
>> y=y+x
>> y=x.*x
>> y=x-x
>>
y=x./(x+x)
Note: "*" and "/" without
"." are matrix multiplication and "matrix division"
(special function of Matlab). For example:
>> P=C*A
A special case applies for scalar multiplication:
>> y=2*x
Many tasks that may be implemented with loop structures
can be more efficiently executed with vectorization. For a complete
description, see MATLAB 5
Technical Note 1109.
Suppose we want to calculate the average value of a
signal over a time interval T, written in the continuous domain as:
![]()
This would be written as a summation in the discrete
domain:
![]()
We can implement this with a for-loop as shown below:
% Generate a
signal
a=0:pi/12:4*pi;
x=sin(a).^2;
% Let's view the
signal
stem(a,x)
xlabel('a');ylabel('x');title('signal')
% now calculate
the average signal value
S=0;
for
k=1:length(x)
S=S+x(k);
end
avg=S/length(x)
Or, more efficiently, we can vectorize the calculation
as shown below:
% Generate a
signal
a=0:pi/12:4*pi;
x=sin(a).^2;
% Let's view the
signal
stem(a,x)
xlabel('a');ylabel('x');title('signal')
% now calculate
the average signal value
avg=sum(x)/length(x)
Graphics
Graphical representation is an important part of
visualizing and understanding signals. The easiest way to graphically display a
signal is by using the plot command:
>> s=[ 1 2
3 4 2 3 5 ];
>> plot(s)
We can represent this data several other ways. A common
way to represent discrete signals is with the stem command:
>> stem(s)
For a complete listing of 2D graphic tools, type:
>> help
plotxy
For a more complete listing of graphic commands, type:
>> help
graphics
All graphs should be clearly labeled as illustrated in
the following example.
EXAMPLE: Plot a discrete-time sinusoid, cos(w n+q
), where w =p /6 and q
=p /6
>>
w=pi/6;theta=pi/3;n=-15:15;
>>
x=cos(w*n+theta);
>> stem(n,x)
This plot should be labeled. To label it, use the
commands:
>>
xlabel('n')
>>
ylabel('x(n)')
>>
title('Discrete-time sinusoid: cos(pi/6*n+pi/3)')
The axes can be set arbitrarily using the axis command.
The argument to the axis command is the vector [XMIN XMAX YMIN YMAX]. For the
above example,
>>
axis([-16 16 -2 2])
would change the scale of the plot. The scale should be
set so that all of the data can be conveniently seen.
More than one plot can be placed on a page using the
subplot command. For more information, type:
>> help
subplot
Finally, to putting a grid on your plot may make things
easier to read. To do this, type:
>> grid
Font control in
plotting: http://www.mathworks.com/support/solutions/solution.layout.html
M-Files
Matlab is most useful when you write your own programs.
You can use any regular ASCII text editor to do so. Simply open a file with the
extension *.m (which is call an m-file) and edit line by line the
sequence of commands you want to include in your program. Save the file and
execute the program by typing the name of the file (without the .m) on your
Matlab command line.
EXAMPLE: Invoke a text editor (e.g. emacs
on UNIX or notepad or the Matlab editor with debugger on PCs) and edit
the following lines:
% This is a
program that generates a noisy signal
x=linspace(0,10*pi,200);
% compute the
signal
y=sin(x);
% compute the
noise
z=0.3*rand(1,200);
% add the noise
y=y+z
% plot the
signal
plot(y);grid
title('Noisy
Sinusoid')
xlabel('x')
ylabel('y')
Save this program for example in a file named noisy.m.
Now, make sure the current directory of Matlab is the directory where the file
is located. You can access this directory by:
(PC)
>> cd M:\ECE360
(UNIX)
>> cd ECE360
You can check the current directory and see a list of
available *.m and *.mat files by executing the commands:
>> pwd
>> what
Finally, execute your program with:
>> noisy
NOTE: You can also write your own function in Matlab (see
the User Functions section.)
User-Defined
Functions
User defined functions work just like commands in
Matlab. In fact, many of the commands are functions written by Matlab
engineers.
From the command line help: >> help function
The function will work like a command from the command
line if:
function [returned_variable_1, returned_variable_2,
…]= function_name(arugments)
EXAMPLE: saved in a file: stat.m
function [mean,stdev]
= stat(x)
n = length(x);
mean = sum(x) / n;
stdev = sqrt(sum((x -
mean).^2)/n);
This function computes the average and the standard
deviation of a vector fed to it in the argument x.
Printing
On a Unix workstation, type setenv PRINTER printername
at the shell prompt before running Matlab. Once in Matlab, typing print
will print out the latest viewed graph.
File
Import/Export
We will generally use variables saved from the Matlab
workspace with the save command. The file will be a "mat" file
(*.mat) and is readable only by Matlab. To import the variables (as you will
need to do for homework) use the command:
>> load filename
The file must be in Matlab's path (see the path
command) or the current directory should be set to the directory containing the
file. (see the M-File section.)
Often, we need to import data from files. For a list of
commands used for io, type:
>> help
iofun
These low-level
commands deal with ASCII files, etc.
Miscellaneous
A list of commands worth checking out
>> help
conv
>> help
sum
>> help
roots
>> help
print
>> help
fft
>> help
fliplr
>> help
sound
>> help
max
>> help
min
>> help
abs
>> help
length
>> help
real
>> help
for
>> help
num2str
>> help
disp
>> help
pause
>> help
whos