ELEC 4810
Introduction to programming in MATLAB
Outline
(1) Getting Started
(2) File I/O
(3) Line Plots
(4) Manipulating Variables
(5) Built-in Functions
Help/Docs
• help
The most important function for learning MATLAB on
your own
• To get info on how to use a function:
» help sin
Help lists related functions at the bottom and links to
the doc
• To get a nicer version of help with examples and easy-to-
read descriptions:
» doc sin
• To search for a function by specifying keywords:
» doc + Search tab
Outline
(1) Getting Started
(2) File I/O
(3) Line Plots
(4) Manipulating Variables
(5) Built-in Functions
Importing Data
• MATLAB is a great environment for processing data. If you
have a text file with some data:
• To import data from files on your hard drive, use
importdata
» a=importdata('textFile.txt');
a is a struct with data, textdata, and colheaders fields
» x=a.data;
» names=a.colheaders;
Writing Excel Files
• MATLAB contains specific functions for reading and writing
Microsoft Excel files
• To write a matrix to an Excel file, use xlswrite
» [s,m]=xlswrite('randomNumbers',rand(10,4),...
'Sheet1'); % we specify the sheet name
• You can also write a cell array if you have mixed data:
» C={'hello','goodbye';10,-2;-3,4};
» [s,m]=xlswrite('randomNumbers',C,'mixedData');
• s and m contain the 'success' and 'message' output of the
write command
• See doc xlswrite for more usage options
Outline
(1) Getting Started
(2) File I/O
(3) Line Plots
(4) Manipulating Variables
(5) Built-in Functions
Plotting
• Example
» x=linspace(0,4*pi,10);
» y=sin(x);
• Plot values against their index
» plot(y);
• Usually we want to plot y versus x
» plot(x,y);
MATLAB makes visualizing data
fun and easy!
What does plot do?
• plot generates dots at each (x,y) pair and then connects the dots
with a line
• To make plot of a function look smoother, evaluate at more points
» x=linspace(0,4*pi,1000);
» plot(x,sin(x));
• x and y vectors must be same size or else you’ll get an error
» plot([1 2], [1 2 3]);
error!!
1 1
10 x values: 1000 x values:
0.8 0.8
0.6 0.6
0.4 0.4
0.2 0.2
0 0
-0.2 -0.2
-0.4 -0.4
-0.6 -0.6
-0.8 -0.8
-1 -1
0 2 4 6 8 10 12 14 0 2 4 6 8 10 12 14
Plot Options
• Can change the line color, marker style, and line style by
adding a string argument
» plot(x,y,’k.-’);
color marker line-style
• Can plot without connecting the dots by omitting line style
argument
» plot(x,y,’.’);
• Look at help plot for a full list of colors, markers, and
linestyles
Multiple Plots in one Figure
• To have multiple axes in one figure
» subplot(2,3,1)
makes a figure with 2 rows and three columns of axes, and
activates the first axis for plotting
each axis can have labels, a legend, and a title
» subplot(2,3,4:6)
activating a range of axes fuses them into one
• To close existing figures
» close([1 3])
closes figures 1 and 3
» close all
closes all figures (useful in scripts/functions)
Outline
(1) Getting Started
(2) File I/O
(3) Line Plots
(4) Manipulating Variables
(5) Built-in Functions
Basic Scalar Operations
• Arithmetic operations (+,-,*,/)
» 7/45
» (1+i)*(2+i)
»1/0
»0/0
• Exponentiation (^)
» 4^2
» (3+4*j)^2
• Complicated expressions, use parentheses
» ((2+3)*3)^0.1
• Multiplication is NOT implicit given parentheses
» 3(1+0.7) gives an error
• To clear command window
» clc
Basic Vector and Matrix Operations
• All the functions that work on scalars also work on vectors
» t = [1 2 3];
» f = exp(t);
is the same as
» f = [exp(1) exp(2) exp(3)];
• If in doubt, check a function’s help file to see if it handles
vectors elementwise
• Operators (* / ^) have two modes of operation
element-wise
standard
Operators: element-wise
• To do element-wise operations, use the dot: . (.*, ./, .^).
BOTH dimensions must match (unless one is scalar)!
» a=[1 2 3];b=[4;2;1];
» a.*b, a./b, a.^b →all errors
» a.*b', a./b’, a.^(b’) →all valid
2 2
Operators: standard
• Multiplication can be done in a standard way or element-wise
• Standard multiplication (*) is either a dot-product or an outer-
product
Remember from linear algebra: inner dimensions must MATCH!!
• Standard exponentiation (^) can only be done on square matrices
or scalars
• Left and right division (/ \) is same as multiplying by inverse
Our recommendation: just multiply by inverse
Outline
(1) Getting Started
(2) File I/O
(3) Line Plots
(4) Manipulating Variables
(5) Built-in Functions
Built-in Functions: Mean
• MATLAB has an enormous library of built-in functions
• Call using parentheses – passing parameter to function
mean
Average or mean value of array
Syntax
M = mean(A)
Description
M = mean(A) returns the mean values of the elements along different
dimensions of an array.
If A is a vector, mean(A) returns the mean value of A.
If A is a matrix, mean(A) treats the columns of A as vectors, returning a
row vector of mean values.
Built-in Functions: Mean Square
mean(Data.^2)
Mean Square
Syntax
Meansqr = mean(Data.^2)
Description
Meansqr = mean(Data.^2) returns the mean square values of the
elements along different dimensions of an array.
If Data is a vector, Meansqr = mean(Data.^2) returns the mean value
of Data.
If Data is a matrix, mean(Data.^2) treats the columns of Data as
vectors, returning a row vector of mean values.
Built-in Functions: Variance
var
Variance
Syntax
V = var(X)
Description
V = var(X) returns the variance of X for vectors. For matrices, var(X)is
a row vector containing the variance of each column of X.
Built-in Functions: Probability
Density Function
In statistics, kernel density estimation (KDE) is a non-parametric way to estimate the
probability density function of a random variable. Kernel density estimation is a fundamental
data smoothing problem where inferences about the population are made, based on a finite
data sample. Kernel density estimates are closely related to histograms, but can be endowed
with properties such as smoothness or continuity by using a suitable kernel. More detailed
description can be found at "http://en.wikipedia.org/wiki/Kernel_density_estimation"
ksdensity
Kernel smoothing density estimate
Syntax
[f,xi] = ksdensity(x)
Description
[f,xi] = ksdensity(x) computes a probability density estimate of the
sample in the vector x. f is the vector of density values evaluated at
the points in xi.
Built-in Functions: Histogram
In statistics, a histogram is a graphical representation
of the distribution of data. It is an estimate of the
probability distribution of a continuous variable and
was first introduced by Karl Pearson. A histogram is a
representation of tabulated frequencies, shown as
adjacent rectangles, erected over discrete intervals
(bins), with an area equal to the frequency of the
observations in the interval. The height of a rectangle
is also equal to the frequency density of the interval,
i.e., the frequency divided by the width of the
interval. The total area of the histogram is equal to
the number of data. A histogram may also be
normalized displaying relative frequencies. It then
shows the proportion of cases that fall into each of
several categories, with the total area equaling 1.
Built-in Functions: Histogram
hist
Histogram plot
Syntax
n = hist(Y)
n = hist(Y,x)
Description
n = hist(Y,x) histogram shows the distribution of data values.
Generate and display a bell-curve histogram from We can change the color of the graph and add the edges
Gaussian data: of the bins of white color. This makes the histogram
x = -4:0.1:4; easily seen:
y = randn(10000,1);
hist(y,x) ; h = findobj(gca,'Type','patch');
However, the displayed histogram is crowded and set(h,'FaceColor','r','EdgeColor','w‘);
details can not be shown.
Built-in Functions: Histogram
How to normalize a histogram, so it is a probability
density (how is that the sum of all bins are equal to 1?).
For a probability density function, the integral over the entire space is 1.
Dividing by the sum will not give you the correct density. To get the right
density, you must divide by the area. To illustrate the point, try the following
example.
[f,x]=hist(randn(10000,1),50);%# create histogram from a normal distribution.
g=1/sqrt(2*pi)*exp(-0.5*x.^2);%# pdf of the normal distribution
%#METHOD 1: DIVIDE BY SUM
figure(1)
bar(x,f/sum(f));hold on
plot(x,g,'r');hold off
%#METHOD 2: DIVIDE BY AREA
figure(2)
bar(x,f/trapz(x,f));hold on
plot(x,g,'r');hold off
Built-in Functions: Histogram
You can see for yourself which method agrees with the correct answer
(red curve).
0.4 0.45
0.35 0.4
0.35
0.3
0.3
0.25
0.25
0.2
0.2
0.15
0.15
0.1
0.1
0.05 0.05
0 0
-4 -3 -2 -1 0 1 2 3 4 5 -4 -3 -2 -1 0 1 2 3 4 5
Devide by sum Devide by area
Want to know more about PDF and Histogram?
http://www.youtube.com/watch?v=yJdiHUqc3eI PDF Operation in Matlab Tutorial
http://en.wikipedia.org/wiki/Histogram Histogram in wikipedia
Built-in Functions: Cross- and auto-
correlation
xcorr
Cross-correlation
Syntax
c = xcorr(x,y,'option')
[c,lags]=xcorr(...)
Description
c = xcorr(x) is the autocorrelation sequence for the vector x.
c = xcorr(x,y,'option') specifies a normalization option for the cross-
correlation, where 'option' is
'biased': Biased estimate of the cross-correlation function
Built-in Functions: Fast Fourier
Transform
fft
Fast Fourier transform
Syntax
Y = fft(x)
Y = fft(X,n)
Description
Y = fft(x) returns the discrete Fourier transform (DFT) of vector x,
computed with a fast Fourier transform (FFT) algorithm.
Y = fft(X,n) returns the n-point DFT. fft(X) is equivalent to fft(X, n)
where n is the size of X in the first nonsingleton dimension. If the
length of X is less than n, X is padded with trailing zeros to length n. If
the length of X is greater than n, the sequence X is truncated. When X
is a matrix, the length of the columns are adjusted in the same manner.
Frequency Domain Waveform
However, due to the many limitations of FFT, we usually use the following
procedure to analyze the frequency characteristics:
Data=your input data in 1D vector;
Frequency=50; %change this value according to your sample frequency.
NFFT = 2^nextpow2( length(data) );
Y = fft(data,NFFT)/length(data);
freq = Frequency/2*linspace(0,1,NFFT/2+1);
figure;
plot(freq,2*abs(Y(1:NFFT/2+1)));
xlabel('Frequency(Hz)');ylabel('Magnitude');
title('Single-Sided Amplitude Spectrum of the data');
Built-in Functions: filter
filter
Filter data with filter object
Syntax
y=filter(hd, x)
Description
y = filter(hm,x) filters a vector of real or complex input data x
through a multirate filter hm, producing filtered output data y
Built-in Functions: define a
bandpass filter
fdesign.bandpass
Bandpass filter specification object
Syntax
D = fdesign.bandpass('Fst1,Fp1,Fp2,Fst2,Ast1,Ap,Ast2',
specvalue1,specvalue2,...)
Description
Frequency response
Fst1 — frequency at the edge of the start of the first stop band.
Fp1 — frequency at the edge of the start of the pass band.
Fp2 — frequency at the edge of the end of the pass band.
Fst2 — frequency at the edge of the start of the second stop band.
% Fst1,Fp1,Fp2,Fst2 specified in normalized frequency units.
Ast1 — attenuation in the first stop band in decibels
Ap — amount of ripple allowed in the pass band. Ast2 —
attenuation in the second stop band in decibels
% Ap, Ast1, Ast2 units dB
Example: bandpass filter (code)
%% Filter a discrete-time signal with a bandpass filter. The signal is a sum of three
discrete-time sinusoids, π/8, π/2, and 3π/4 radians/sample.
n = 0:159;
x = cos(pi/8*n)+cos(pi/2*n)+sin(3*pi/4*n);
%% Design an FIR equiripple bandpass filter to remove the lowest and highest discretetime sinusoids.
d = fdesign.bandpass('Fst1,Fp1,Fp2,Fst2,Ast1,Ap,Ast2',1/4,3/8,5/8,7/8,60,1,60);
Hd = design(d,'equiripple');
%% Apply the filter to the discrete-time signal.
y = filter(Hd,x);
freq = 0:1/length(x):0.5;
xdft = fft(x);
ydft = fft(y);
figure;plot(freq,abs(xdft(1:length(x)/2+1)));
hold on;
plot(freq,abs(ydft(1:length(x)/2+1)),'r','linewidth',2);
legend('Original Signal','Bandpass Signal');
xlabel('Freq(Hz)');ylabel('Mag.(dB)');
%% pulse response
whitenoise=zeros(size(n));
whitenoise(1)=1; % pulse signal
yn=filter(Hd,whitenoise);
yndft=fft(yn);
figure;
plot(freq,10*log(abs(yndft(1:length(x)/2+1))));
legend('freq response');
xlabel('Freq(Hz)');ylabel('Mag.(dB)')
Example: bandpass filter (result)
90 20
Original Signal freq response
80 Bandpass Signal
0
70
60 -20
Mag.(dB)
Mag.(dB)
50
-40
40
30 -60
20
-80
10
0 -100
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5 0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5
Freq(Hz) Freq(Hz)
Fourier transform of original signal and bandpass signal Frequency response of designed bandpass filter