Matlab Slides 2up PDF
Matlab Slides 2up PDF
Markus Kuhn
Computer Laboratory
Michaelmas 2011
What is MATLAB
→ high-level language (garbage collecting, var-len structures)
→ BASIC-like syntax, with elements from C, GUI IDE
→ basic data type: 2- or 3-dimensional floating-point matrix
→ most operators and functions work on entire matrices
⇒ hardly ever necessary to write out loops
→ uses internally highly optimized numerics libraries
(BLAS, LAPACK, FFTW)
→ comprehensive toolboxes for easy access to standard algorithms
from many fields: statistics, image processing, signal process-
ing, neural networks, wavelets, communications systems
→ very simple I/O for many data/multimedia file formats
→ popular for experimental/rapid-prototype number crunching
→ widely used as a visualization and teaching tool
2
What MATLAB is not
→ not a computer algebra system
→ not a strong general purpose programming language
• limited support for other data structures
• few software-engineering features;
typical MATLAB programs are only a few lines long
• not suited for teaching OOP
• limited GUI features
→ not a high-performance language (but fast matrix operators)
→ not freely available
Some of these limitations have been reduced in recent releases, e.g.
release 13 replaced slow interpreter with a JIT compiler (JVM).
Free alternatives: GNU Octave (http://www.gnu.org/software/octave/) reimplements a MAT-
LAB subset. SciLab (http://www.scilab.org/) is another MATLAB-like package. R specializes
on statistics and plotting (http://www.r-project.org/). Python, a full-featured programming
language, has with its numpy and matplotlib packages (http://matplotlib.sourceforge.net/)
also evolved into a serious competitor and MATLAB-lookalike.
3
8
MATLAB matrices (5)
>> [2 3 5] * [1 7 11]'
>> [1 1; 1 0] * [2 3]'
ans =
ans =
78
5
>> [2 3 5]' * [1 7 11]
2
ans =
>> [1 2 3] .* [10 10 15]
2 14 22
ans =
3 21 33
10 20 45
5 35 55
√
The imaginary unit vector −1 is available as both i and j, and
matrices can be complex.
Related functions: real, imag, conj, exp, abs, angle
0.7 0.6
0.6 0.4
0.5
0.2
0.4
0.3 0
0.2
−0.2
0.1
0 −0.4
0 5 10 15 20 0 2 4 6 8 10
x = 0:20; t = 0:0.1:10;
y = 0.5 - 0.5*cos(2*pi * x/20); x = exp(t * (j - 1/3));
stem(x, y); plot(t, real(x), t, imag(x));
title('20-point raised cosine'); grid; legend('real', 'imaginary')
2D plotting
−20
1
−15
0.5
−10
0
−5
−0.5 0
20
20
0 10
0 5
−10
−20 −20
10
15
xl = -20:0.3:20;
yl = -20:0.3:20; 20
[x,y] = meshgrid(xl, yl); −20 −10 0 10 20
r = sqrt(x.^2 + y.^2);
s = sin(r) ./ r; s(find(r==0)) = 1; imagesc(xl, yl, s, [-1 1]);
plot3(x, y, s); colormap(gray);
grid on; set(gca, 'DataAspectRatio', [1 1 1]);
12
Some common functions and operators
*, ^ imread, imwrite, image,
matrix multiplication, exponentiation imagesc, colormap
/, \, inv bitmap image I/O
A/B = AB −1 , A\B = A−1 B, A−1 plot, semilog{x,y}, loglog
+, -, .*, ./, .^ 2D curve plotting
element-wise add/sub/mul/div/exp conv, conv2, xcorr
==, ~=, <, >, <=, >= 1D/2D convolution,
relations result in element-wise 0/1 cross/auto-correlation sequence
length, size fft, ifft, fft2
size of vectors and matrices
discrete Fourier transform
zeros, ones, eye, diag
sum, prod, min, max
all-0, all-1, identity, diag. matrices
sum up rows or columns
xlim, ylim, zlim
set plot axes ranges cumsum, cumprod, diff
xlabel, ylabel, zlabel cumulative sum or product,
label plot axes differentiate row/column
wavread, wavwrite, sound find
audio I/O list non-zero indices
csvread, csvwrite figure, saveas
comma-separated-value I/O open new figure, save figure
13
15
3500
3000
2500
Frequency
2000
1500
1000
500
0
0.5 1 1.5 2 2.5
Time
16
Example solution:
t = 0:1/fs:d-1/fs; % timestamps for each sample point
% normalized logarithm of frequency of each tone (row)
% for each sample point (column), all rising linearly
% from 0 to 1, then wrap around back to 0
l = mod(([0:n-1]/n)' * ones(1, fs*d) + ones(n,1) * (t/(d*n)), 1);
f = fmin * (fmax/fmin) .^ l; % freq. for each tone and sample
p = 2*pi * cumsum(f, 2) / fs; % phase for each tone and sample
% make last column a multiple of 2*pi for phase continuity
p = diag((2*pi*floor(p(:,end)/(2*pi))) ./ p(:,end)) * p;
s = sin(p); % sine value for each tone and sample
% mixing amplitudes from raised-cosine curve over frequency
a = 0.5 - 0.5 * cos(2*pi * l);
w = sum(s .* a)/n; % mix tones together, normalize to [-1, +1]
17
Exercise 5 (a) Write down the function g(t) that has the shape of a sine
wave that increases linearly in frequency from 0 Hz at t = 0 s to 5 Hz at
t = 10 s.
(b) Plot the graph of this function using MATLAB’s plot command.
(c) Add to the same figure (this can be achieved using the hold command)
in a different colour a graph of the same function sampled at 5 Hz, using
the stem command.
(d) Plot the graph from (c) separately. Try to explain its symmetry (hint:
sampling theorem, aliasing).