Matlab Signal Processing Examples
Matlab Signal Processing Examples
file:///C:/Documents%20and%20Settings/Dave.Dorran/My%20Documen...
The load command can also be used to read in previously saved matlab workspaces
len_ecg = length(ecg_sig);
1 of 20
15/11/2012 06:50
file:///C:/Documents%20and%20Settings/Dave.Dorran/My%20Documen...
Name
ecg_sig
len_ecg
Size
6000x1
1x1
Bytes
Class
48000
8
double
double
Attributes
2 of 20
15/11/2012 06:50
file:///C:/Documents%20and%20Settings/Dave.Dorran/My%20Documen...
then used to actual write data to the file using the fprintf function. Finally the file should be closed.
fid = fopen('test.txt', 'w' ); % open for overwriting
a = 5;
fprintf(fid, 'The value of the variable a is %d', a);
fprintf(fid, '\n\tBye Bye!!'); % put a newline (\n) and tab (\t) before Bye Bye
fclose(fid);
A demo of appending information to a file
x =
0
Ex. 2
x = 0 : 1 : 7
x =
0
Ex. 3
x = 1 : 0.25 : 2
3 of 20
15/11/2012 06:50
file:///C:/Documents%20and%20Settings/Dave.Dorran/My%20Documen...
x =
1.0000
1.2500
1.5000
1.7500
99.3400
99.0100
2.0000
Ex. 4
x = 100 : -0.33 : 99
x =
100.0000
99.6700
As stated above the basic format for using the colon operator is the following:
starting_value : step_size : last_value_limit
This format is used for Ex. 2, 3 and 4, however if the step_size is ommitted (as is the case in Ex. 1)
then the step_size defaults to 1. It should be appreciated that Ex. 2 produces the same values as Ex.1
since the step_size is explicitly set to 1.
Part 2 - Segment Selection
The colon operator is used frequently to select a range of values from a discrete signal. Here are a few
examples.
Ex. 1
x = [12 34 4 5 6 78 8 9 2];
seg = x(3:5) % select from sample 3 to sample 5
seg =
4
Ex. 2
x = [12 34 4 5 6 78 8 9 2];
seg = x(3:end) % select from sample 3 to the last sample
seg =
4
78
4 of 20
15/11/2012 06:50
file:///C:/Documents%20and%20Settings/Dave.Dorran/My%20Documen...
document on common signal processing functions). The previous section (the colon operator) also
showed how to create a ramp signal and a sinuoid. This section is divided into four parts: Part 1 shows
how to create a signal given any arbitrary mathemtical expression for a signal; Part 2 shows how to
create combine signals through concatenation and summing; Part 3 shows how to create a periodic
signal given any arbitrary period of a signal
Part 1 - Synthesis Using a Mathematical Expression
Given a mathematical expression for a signal x(t) then the discrete version of this signal is given by x[n]
= x(nT) where n is the sample number and T is sampling period.
Here are two examples of this formula being applied:
Ex. 1 T = 0.0001; % sampling period in seconds
n = 0 : 10000; %n is the sample number
x = exp(-pi*n*T) + 5*sqrt(cos(n*T));
t = n*T;
plot(t,x)
xlabel('Time (seconds)');
ylabel('Amplitude');
Ex. 2 -
where
and
5 of 20
15/11/2012 06:50
file:///C:/Documents%20and%20Settings/Dave.Dorran/My%20Documen...
w =
8
10
13
10
w =
1
6 of 20
15/11/2012 06:50
file:///C:/Documents%20and%20Settings/Dave.Dorran/My%20Documen...
x = [3 ; 2 ; 6];
y = [1 ; 9];
w = [x ; y]
w =
3
2
6
1
9
7 of 20
15/11/2012 06:50
file:///C:/Documents%20and%20Settings/Dave.Dorran/My%20Documen...
8 of 20
15/11/2012 06:50
file:///C:/Documents%20and%20Settings/Dave.Dorran/My%20Documen...
The following plot shows that there regions of strong spectral energy. These regions correspond to the
frequencies of the fundamentals and harmonics of the notes being played on the guitar.
low_freq_mags = mag_ft(1:2000); %the magnitudes of the low freq content are stored in a new variable
%Note: 2000 in the above command corresponds to 2000/length(mag_ft)*fs = 400Hz
plot(low_freq_mags);
ylabel('Magnitude/Amplitude')
xlabel('Bin Number')
9 of 20
15/11/2012 06:50
file:///C:/Documents%20and%20Settings/Dave.Dorran/My%20Documen...
Oftentimes its useful to show the actual frequencies rather than bin numbers on the x axis. After taking
the fft of a signal each frequency bin is separated by fs/(N-1) Hz where fs is the sampling frequency (Hz)
and N is the number of frequency bins i.e. length(mag_ft) in the example above.
N = length(mag_ft);
freq_scale = 0: fs/(N-1) : fs;
plot(freq_scale, mag_ft);
ylabel('Magnitude/Amplitude')
xlabel('Frequency (Hz)')
10 of 20
15/11/2012 06:50
file:///C:/Documents%20and%20Settings/Dave.Dorran/My%20Documen...
Since low_freq_mags was extracted from mag_ft the same frequency spacing exists between the bins of
low_freq_mags. Note that the length of the frequency scale must be the same as the length of the
magnitude vector being plotted.
low_mag_freq_scale = freq_scale(1:length(low_freq_mags));
plot(low_mag_freq_scale, low_freq_mags);
ylabel('Magnitude/Amplitude')
xlabel('Frequency (Hz)')
11 of 20
15/11/2012 06:50
file:///C:/Documents%20and%20Settings/Dave.Dorran/My%20Documen...
Here's an example of analysing the frequency content of the first note in the bass guitar recording.
First analyse the time-domain signal to determine where the first note ends
plot(bass_guitar);
ylabel('Amplitude')
xlabel('Sample Number')
12 of 20
15/11/2012 06:50
file:///C:/Documents%20and%20Settings/Dave.Dorran/My%20Documen...
It can be seen that the first note ends at around sample 38000
first_note = bass_guitar(1:38000); %exrtact the first note from the signal
ft_first_note = fft(first_note);
mags = abs(ft_first_note);
freq_scale = 0: fs/(length(mags) -1) : fs;
determine the bin corresponding to 400Hz. Just display those frequency bins. The plot shows the
fundamental at 73Hz with two strong harmonics at 146Hz and 219Hz
low_freq_bin_range = length(mags)*(400/44100);
low_freq_mags = mags(1:low_freq_bin_range);
low_freq_scale = freq_scale(1: low_freq_bin_range);
plot(low_freq_scale, low_freq_mags)
ylabel('Magnitude/Amplitude')
xlabel('Frequency (Hz)')
Warning: Integer operands are required for colon operator when used as index
Warning: Integer operands are required for colon operator when used as index
13 of 20
15/11/2012 06:50
file:///C:/Documents%20and%20Settings/Dave.Dorran/My%20Documen...
14 of 20
15/11/2012 06:50
file:///C:/Documents%20and%20Settings/Dave.Dorran/My%20Documen...
is often the case that each instrument is recorded in isolation in a sound proof anechoic (echo free)
environment. Then the individual recordings are added together (mixed) before finally adding an effect
which makes the music sound as if it were recorded in a large venue which has musically pleasing
reverberation. This is done by convolving the music with the impulse response of appropriate venues; for
example Carnegie Hall or the Sydney Opera House. This makes the music sound as if it was actually
recorded in these venues. The impulse response of these venues is effectively just a recording of the
venue after a pseudo audio impulse is played i.e. a loud short bang and they are easily obtained. Here's
some example code to try out
[church_impulse fs] = wavread('church.wav'); % read in a previously recorded
impulse response of a church available from http://eleceng.dit.ie/dorran/matlab/church.wav
my_speech = wavrecord(2*fs, fs, 1); % record 2 seconds of speech
my_speech_in_church = conv(my_speech, church_impulse);
sound(my_speech_in_church, fs); %play back the recording. It should sound like
%you are speaking in a church
In this second example it'll be shown that convolution produces the same output as the filter function
above. To do this the impulse response of the above system will first be determined using the impz
fucntion.
x = [ 2 4 5 23 1 34 5] ; % an example signal
b = [0.3 1.5];
a = [1 -0.6];
h = impz(b,a);
y2 = conv(x,h);
% compare y2 with y above. They should be the same.
Using frequency-domain multiplication
The frequency content of the output of a system is equal to the fequency content of the input multiplied
by the frequency response of the system i.e. Y(k) = X(k).H(k), where k represents the bin number.
Once Y(k) is determined the time-domain output can be obtained by taking the inverse DFT using the
ifft function. It is important to note that in order for this technique to work the number of frequency
bins used in determining Y(k) must be at least as long as the number of non-zero values in y[n] i.e. the
length of the input plus the length of the impulse response. If this rule is not observed unusual (but
explainable) results will occur.
Note that the frequency response of a system might be obtained in any number of ways
%(see section on determing a systems frequency response). In this example the frequency
%response of the example system above will be determined by taking the DFT of the systems
%impulse response, simply to show that the technique of frequency domain multiplication works.
x = [ 2 4 5 23 1 34 5] ; % an example signal
b = [0.3 1.5];
a = [1 -0.6];
h = filter(b,a, [ 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ]); %determine the impulse response % alternatively use |impz| to calculate h
num_bins = length(x) + length(h); % this is minimum number of bins that should be uesed to determin
H = fft(h, num_bins);
X = fft(x, num_bins);
Y = X.*H;
y3 = ifft(Y);
y3 = real(y3); % usually there will be some very small imaginary terms in the y value - these are ba
% introduced due to rounding errors and should be ignored.
%
% compare y3 with y and y2 above. They should be the same.
15 of 20
15/11/2012 06:50
file:///C:/Documents%20and%20Settings/Dave.Dorran/My%20Documen...
16 of 20
15/11/2012 06:50
file:///C:/Documents%20and%20Settings/Dave.Dorran/My%20Documen...
The following evaluates this expression for 200 points around the unit circle i.e. theta is varied from 0 to
pi in steps of pi/(200-1);
theta = 0 : pi/(200-1) : pi;
z = exp(j*theta);
H = (z + 2)./(z.^2 -z + 0.3);
%compare with freqz evaluated for 200 bins
b = [1 2];
a = [1 -1 0.3];
H2 = freqz(b,a, 200);
plot(abs(H));
hold on
plot(abs(H2),'rx')
hold off
Designing Filters
There are lots of filter design techniques available (fir1, chebyshev, butterworth, elliptical) and matlab
has functions which design filters using these techniques.
Each filter design technique has its own set of pro's and con's (see
http://answers.yahoo.com/question/index?qid=20101017195425AAxy47e for info on IIR filters) and the
17 of 20
15/11/2012 06:50
file:///C:/Documents%20and%20Settings/Dave.Dorran/My%20Documen...
Design a bandpass filter using the three IIR techniques - 3rd order
18 of 20
15/11/2012 06:50
file:///C:/Documents%20and%20Settings/Dave.Dorran/My%20Documen...
Design a bandpass filter using the three IIR techniques - 6th order
[b_butter, a_butter] = butter(6, [0.2 0.5]);
[b_cheby, a_cheby] = cheby1(6, 0.5, [0.2 0.5]); % 0.5 paramter specfies passband ripple
[b_ellip, a_ellip] = ellip(6 ,0.5, 20, [0.2 0.5]); % 20 parameter specifies stopband ripple
H_butter = freqz(b_butter, a_butter, 200);
H_cheby = freqz(b_cheby, a_cheby, 200);
H_ellip = freqz(b_ellip, a_ellip,200);
plot(abs(H_butter))
hold on
plot(abs(H_cheby), 'r');
plot(abs(H_ellip), 'g');
xlabel('Frequency bins');
ylabel('Magnitude');
legend('butter', 'cheby', 'ellip')
hold off
19 of 20
15/11/2012 06:50
file:///C:/Documents%20and%20Settings/Dave.Dorran/My%20Documen...
20 of 20
15/11/2012 06:50