MATLAB Crash Course
MATLAB Crash Course
Objective: To learn the basics of the MATLAB software for DSP applications.
Background information:
MATLAB is both a computer programming language, and an environment for simulating,
analysing and designing signals and systems. ‘MATLAB’ is a contraction of ‘MATrix
LABoratory’. The basic entity in MATLAB is a matrix, an m �n array of variables, written in
general as:
What did you observe in the MATLAB window? You can see that MATLAB can be
used as a calculator!
_____________________________________________________________________
Now, type:
>>A=6
_____________________________________________________________________
_____________________________________________________________________
In MATLAB, all variables are matrix arrays (simple scalar variables, and row and
column vectors can be thought of as special cases of a matrix).
Type:
>>B=[1 2 3; 4 5 6]
1 2 3�
�
The MATLAB window will show the matrix B: B = �
4 5 6�
� �
Type:
>>C=[1 2 3; 4 5 6];
Now C has the same value as B. However, with “;” added at the end of the command
line, MATLAB no longer echoes what you typed in the command window.
At this point, can you list out all the variables that you have in your workspace?
Which MATLAB command should you use?
_____________________________________________________________________
To see the contents of the variables, type their names, and record what you observe.
>>A
>>B
>>C
_____________________________________________________________________
What would happen (and why) if you were to type the following command? Try it.
_____________________________________________________________________
Type:
>>C=[3 4 5 6 7 8 9]
Type:
>>D=[3:1:9]
Is D identical to C?
_____________________________________________________________________
In the expression, [3:1:9], the “3” represents the first element of a vector, the “1” is
the incremental step, and the “9” is the last element of the vector. Now type:
>>E=[9:-1:3]
Type:
>>F=[9:-2:3]
You can also extract an element or a sub-matrix from a matrix. Type the following:
>>D(3)
>>D(2:4)
>>B(2,2)
>>B(1,2:3)
>>B(1,:)
>>B(2,:)
>>B(:,1)
>>B(:,3)
Write down the value of G. Can you explain how this value comes about?
_____________________________________________________________________
Type:
_____________________________________________________________________
Type:
>>D*D'
Write down the answer. Can you explain how this value comes about?
_____________________________________________________________________
Type:
>>TMP=[2 4 6; 3 5 7]'
_____________________________________________________________________
Type:
>>B*TMP
_____________________________________________________________________
Note that in matrix multiplication, the dimensions of the two matrices should always
fit each other, i.e. mn followed by nm.
You can also find the inverse of a square matrix with the help of MATLAB
Type:
>>H=[2 4; 3 1]
>>INVH=inv(H)
_____________________________________________________________________
Type:
>>I=H*INVH
_____________________________________________________________________
For the other two expressions, can you verify your result by hand?
_____________________________________________________________________
_____________________________________________________________________
Type:
>>B./TMP'
_____________________________________________________________________
Note that addition and subtraction are always element-wise (unlike multiplication and
division).
Type:
>>A=[1 3 2];
>>roots(A)
_____________________________________________________________________
What are the roots of the above equation? Verify your result by hand.
_____________________________________________________________________
>>help roots
What happens?
_____________________________________________________________________
Some other builtin functions can help you extract or insert numbers in a vector.
Type:
>>J=[ones(1,4),[2:2:11],zeros(1,3)]
>>length(J)
>>J(2:2:length(J))
Explain the results you obtained at each stage.
_____________________________________________________________________
Many tools for drawing graphics are also available. As an example, see how a simple
threedimensional graph can be displayed.
Type and watch:
>>[X,Y,Z]=sphere(20);
>>mesh(X,Y,Z)
>>hold
>>mesh(X+10,Y+10,Z)
t=[1:1:100];
s=sin(4*pi*t/100);
plot(t,s);
Go to the "File" menu, select "Save as" and type in the name of the file as “testmat”
(or any other filename that you wish). This file will be saved as "testmat.m". In the
MATLAB command window, type:
>>testmat
_____________________________________________________________________
2-2. Loops
In MATLAB programs (M-files), you can also construct loops. Try the following
program (you may name it testloop.m), and describe what happens:
A=[1 3 2; 1 –3 2; 2 5 2];
for index=1:3,
Aroots=roots(A(index,:))
end
_____________________________________________________________________
t=[1:1:100];
s=sin(4*pi*t/100);
subplot(2,1,1),
plot(t,s);
axis([0 100 -1.5 1.5]);
grid on;
rec_s=abs(s);
subplot(2,1,2),
plot(t,rec_s);
axis([0 100 -1.5 1.5]);
grid on;
What waveform is signal "rec_s?" What do the commands "subplot," "axis," "grid on"
do? (Hint: use online help).
_____________________________________________________________________
t=[1:1:100];
s=sin(4*pi*t/100);
subplot(2,1,1),
plot(t,s);
axis([0 100 -1.5 1.5]);
grid on;
doub_s=s.*s;
subplot(2,1,2),
plot(t,doub_s);
axis([0 100 -1.5 1.5]);
grid on;
t=-2:0.05:3;
x=sin(2*pi*0.789*t)
plot(t,x), grid on
title(‘Test plot of Sinusoid’)
xlabel(‘Time(sec)’)
ylabel(‘Amplitude(volt)’)
Now amend the program to plot a new signal y = 0.75cos(20.789t) on top of the
previous one (type “help plot” to see the plot format to find out how to show multiple
signals in the same frame). Use the “save and run” ikon in the toolbar when amending
existing programs.
Exercise 1
Plot a signal u(t) which is the sum of a sine signal x 1(t), with amplitude of 0.8 volt,
frequency of 1000 Hz and phase shift of zero and another sine wave x2(t) with
amplitude of 0.6 volt, frequency of 2500 Hz and phase shift of 45 {i.e. u(t) = x1(t) +
x2(t)}. Hint: Use time index, t=[0:1:39]/20000.
Exercise 2
Plot the magnitude and phase of the following expression for 0 2:
H = 1 0.3e j
2-4. Functions
M-files can be either scripts or functions. Scripts are simply program files containing a
sequence of MATLAB statements. Functions (called from a script or another function) make
use of their own local variables, accept input arguments and deliver output values back to the
point where they were called. A line at the top of a function M-file contains the syntax
definition. The name of a function, as defined in the first executable line of the M-file, should
be the same as the name of the file without the “.m” extension.
Example:
The following script, “mainFIR.m”, is a “main program”, and calls the specially-written (not
built-in) functions “delta.m” and “lp2hp.m”. Functions can call other functions, (both built-in
and specially-written) and in this example “lp2hp.m” calls “delta.m”. Check that functions
“delta.m” and “lp2hp.m” are not built-in functions, by typing “help delta” and “help lp2hp”.
The purpose of the main program is to design an FIR linear phase filter, using the built-in
function “fir1.m” (type “help fir1” in the command window to understand the syntax of the
fir1.m function). The impulse response and the amplitude of the frequency response of this
lowpass filter are then evaluated and plotted. The linear phase lowpass filter is then converted
to a linear phase highpass filter by means of a simple transformation between the impulse
responses. In an obvious notation: hH [n] = d [n M ] hL [ n] , where M is the midpoint of the
impulse responses. (This only works when the common length of the impulse responses is
odd, and when the lowpass filter has 0 dB gain at DC: why?).
The main program and the two functions need to be in the same directory, where they can
“see one another”. Note the use of non-executable comments (% … ) to annotate the code:
these should be plentiful enough to make the code self-explanatory long after it was first
written.
% mainFIR.m
% This main program designs a LPF,
% converts it to a HPF, and
% plots impulse and frequency
% responses of both filters.
clear;clc;
for k = 1:2
figure(k)
clf
end
% lp2hp.m
% Convert LPF to HPF by subtracting
% LPF impulse response from a unit
% impulse at its midpoint.
function hH = lp2hp(Lb,hL)
LhL = length(hL);
if rem(Lb,2) == 0
disp('Does not work for even length')
else
midpoint = (Lb+1)/2;
end
imp = delta(midpoint,LhL);
hH = imp - hL;
Exercise 3
Show, by adding further commands to the “mainFIR.m” program, that direct design of
a highpass filter using the fir1.m function gives rise to a better frequency response.
This shows that the fir1.m function definitely does not use the lowpass-to-highpass
transformation technique implemented in “lp2hp.m”.
Exercise 4
By adding further commands to the “mainFIR” program, generate and plot (in
additional figures) the phase versus frequency characteristics of each of the two
filters. Remember to modify the “housekeeping” commands at the top of the main
program, used to clear the figures before program execution. Are the filters linear
phase? If so, why?
It is not necessary, from the point of view of understanding how specially-written functions
work, to understand the detail of the use of the filter design (fir1.m) and fast Fourier
transform (fft.m and fftshift.m): the user can still run the main program and check that the
results make sense. For learning the basics of MATLAB , the main point is to notice how the
functions are called (indicated by red in the code given above), and how the syntax of each
function is defined in the function header.
On the other hand, for those who are also learning the digital signal processing applications
of MATLAB, this example is a good illustration of some fundamental DSP concepts: filter
design and evaluation in the time-domain and frequency-domain.