Introduction To Matlab
Introduction To Matlab
Preetham Shankpal Asst. Professor, M S Ramaiah School of Advanced Studies Email: preetham@msrsas.org
Introduction
What is Matlab? MATrix LABoratory. MATLAB is a numerical computing environment and programming language (initially written in C). MATLAB allows easy matrix manipulation, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs in other languages.
Powerful, extensible, highly integrated computation, programming, visualization, and simulation package
MATLAB Toolboxes
HELP WINDOW - DEMOS
Signal & Image Processing Signal Processing Image Processing Communications Frequency Domain System Identification Higher-Order Spectral Analysis System Identification Wavelet Filter Design Control Design Control System Fuzzy Logic Robust Control -Analysis and Synthesis Model Predictive Control
Math and Analysis Optimization Requirements Management Interface Statistics Neural Network Symbolic/Extended Math Partial Differential Equations PLS Toolbox Mapping Spline Data Acquisition and Import Data Acquisition Instrument Control Excel Link Portable Graph Object
MATLAB System
Language: arrays and matrices, control flow, I/O, data structures, user-defined functions and scripts Working Environment: editing, variable management, importing and exporting data, debugging, profiling Graphics system: 2D and 3D data visualization, animation and custom GUI development Mathematical Functions: basic (sum, sin,) to advanced (fft, inv, Bessel functions, ) One can use MATLAB with C, Fortran, and Java, in either direction
References
Mastering MATLAB 7, D. Hanselman and B. Littlefield, Prentice Hall, 2004
Getting Started with MATLAB 7: A Quick Introduction for Scientists and Engineers, R. Pratap, Oxford University Press, 2005.
Desktop Tools
Command Window type commands Workspace view program variables clear to clear double click on a variable to see it in the Array Editor Command History view past commands save a whole session using diary
8
10
11
Matrix analysis. norm - Matrix or vector norm. normest - Estimate the matrix 2-norm. rank - Matrix rank. det - Determinant. trace - Sum of diagonal elements. null - Null space. orth - Orthogonalization. rref - Reduced row echelon form. subspace - Angle between two subspaces.
12
Bytes 8 8 8
Attributes
13
14
Matlab as Calculator
The basic arithmetic operators are + - * / ^ and these are used in conjunction with brackets: ( ) The symbol ^ is used to get exponents (powers): 2^4=16 You should type in commands shown following the prompt: >>. >> 2+3/4*5
ans =
5.7500
15
Matlab as Calculator
Is this calculation 2 + 3/(4*5) or 2 + (3/4)*5? Matlab works according to the priorities: 1. quantities in brackets, 2. powers 2 + 3^2 ==> 2 + 9 = 11, 3. * /, working left to right (3*4/5=12/5), 4. + -, working left to right (3+4-5=7-5), Thus, the earlier calculation was for 2 + (3/4)*5 by priority 3
16
Matlab as Calculator
>> 16 + 24 ans = 40
no declarations needed
>> product = 16 * 23.24 product = 371.84 >> product = 16 *555.24; >> product product = 8883.8
17
MATLAB Data
The basic data type used in MATLAB is the double precision array
No declarations needed: MATLAB automatically allocates required memory Resize arrays dynamically To reuse a variable name, simply use it in the left hand side of an assignment statement
18
The e notation is used for very large or very small numbers: -1.3412e+03 = -1.3412 x103 = -1341.2 -1.3412e-01 = -1:3412 10-1 =-0.13412 All computations in MATLAB are done in double precision, which means about 15 significant figures The format how Matlab prints numbers is controlled by the format command
M S Ramaiah School of Advanced Studies
19
20
Variable Names
Legal names consist of any combination of letters and digits, starting with a letter. These are allowable: NetCost, Left2Pay, x3, X3, z25c5 These are not allowable: Net-Cost, 2pay, %x, @sign User names that reflect the values they represent Special names: you should avoid using eps = 2.2204e-16 =2-54 (The largest number such that 1 + eps is indistinguishable from 1) and pi = 3.14159... = . If you wish to do arithmetic with complex numbers, both i and j have the value -1 unless you change them
21
Variable Basics
clear all; close all; clc; product = 2 * 3^3; comp_sum = (2 + 3i) + (2 - 3i); show_i = i^2; save abc_1 clear load abc_1 who Solve in MATLAB
22
Variables Revisited
Variable names are case sensitive and over-written when re-used Basic variable class: Auto-Indexed Array
Allows use of entire arrays (scalar, 1-D, 2-D, etc) as operands Vectorization: Always use array operands to get best performance (avoiding for loops)
Terminology: scalar (1 x 1 array), vector (1 x N array), matrix (M x N array)
Special variables/functions: ans, pi, eps, inf, NaN, i, nargin, nargout, varargin, varargout, ... Commands who (terse output) and whos (verbose output) show variables in Workspace
23
Suppressing Output
One often does not want to see the result of intermediate calculations terminate the assignment statement or expression with semicolon
>> x=-13; y = 5*x, z = x^2+y y= -65.00 z= 104.00
the value of x is hidden. Note also we can place several statements on one line, separated by commas or semicolons
24
Trigonometric Functions
Those known to Matlab are sin, cos, tan and their arguments should be in radians. e.g. to work out the coordinates of a point on a circle of radius 5 centred at the origin and having an elevation 30o = pi/6 radians.
>> x = 5*cos(pi/6), y = 5*sin(pi/6) x= 4.33 y= 2.50
The inverse trig functions are called asin, acos, atan (as opposed to the usual arcsin or sin-1 etc.). The result is in radians.
acos(x/5), asin(y/5) ans = 0.52 ans = 0.52
26
5.00
27
Row Vectors
We can do certain arithmetic operations with vectors of the same length, such as v and v3 in the previous section
>> v, v3, v+v3 v= 1.00 v3 = 3.00 ans = 4.00
2.24 5.00 7.24 >> v, v2, v+v2 v= 1.00 3.00 2.24 v2 = 7.00 5.00 ??? Error using ==> plus Matrix dimensions must agree.
28
Row Vectors
A vector may be multiplied by a scalar (a number see v4), or added/subtracted to another vector of the same length. The operations are carried out element wise
>> v, v4=3*v v= 1.00 v4 = 3.00
3.00 9.00
2.24 6.71
3.00
-1.00 -1.00
-2.00 16.00
-3.00 18.00
29
Row vectors
We can also change or look at the value of particular entries
w(2) = -2, w(3) w= 1.00 -2.00 ans = 3.00
3.00
30
>> a= 1:4 a= 1.00 2.00 >> b=3:7 b= 3.00 4.00 >> c=-1:1 c= -1.00 0 >> d=1:-1 d= Empty matrix: 1-by-0
3.00
4.00
5.00
6.00
7.00
1.00
4.00
7.00
More generally a : b : c produces a vector of entries starting with the value a, incrementing by the value b until it gets to c (it will not produce a value beyond c). This is why 1:-1 produced the empty vector [].
M S Ramaiah School of Advanced Studies
31
5.00
-1.00
-3.00
-5.00
-7.00
-3.00
-5.00
5.00
-3.00
-7.00
-1.00
3.00
32
Column Vectors
These have similar constructs to row vectors. When defining them, entries are separated by ; or newlines
>> a= [1; 2; 3] a= 1.00 2.00 3.00 >> b = [ 1 2 3] b= 1.00 2.00 3.00
so column vectors may be added or subtracted provided that they have the same length
M S Ramaiah School of Advanced Studies
33
Transposing a Matrix
We can convert a row vector into a column vector (and vice versa) by a process called transposing denoted by . >> a = [1 2 3]
a= 1.00 2.00 3.00
Plot(t, sin(2*pi*100*t))
2
clear all; clc f=100; fs=40*f; ts=1/fs; t=0:ts:1; w=2*pi*f; y=3*sin(w*t); plot(t,y)
-1
-2
-3
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
-1
-2
-3
0.01
0.02
0.03
0.04
0.05
0.06
0.07
35
Multiple Plots
3
plot(t,sin(wt), t,cos(wt))
-1
-2
-3
0.01
0.02
0.03
0.04
0.05
0.06
0.07
0.08
0.09
0.1
4 2 0 -2 -4
0.01
0.02
0.03
0.04
0.05
0.06
0.07
0.08
0.09
0.1
4 2 0 -2 -4
0.01
0.02
0.03
0.04
0.05
0.06
0.07
0.08
0.09
0.1
36
Vectorization Example*
tic; x=0.1; for k=1:199901 y(k)=besselj(3,x) + log(x); x=x+0.001; end toc;
Elapsed time is 17.092999 seconds.
37
2D MATRIX Declaration
M=[3 4 5; 6 7 8; 1 -1 0]
>> a=[1;2;3]; >> b=[3;4;5]; >> c=[2;3;4]; >> s=[a b c] s= 1.00 2.00 3.00
M=magic(4)
38
Interestingly, Durer also dated this engraving by placing 15 and 14 side-byside in the magic square.
39
40
Matrix Manipulations
Scalar Product (*) u= [ 1 2 3]; v= [2;3;4] ; uv ui vi i 1 Scalar_product= 1x2+2x3+3x4=20
>> u= [ 1 2 3]; v= [2;3;4]; >> u*v ans = 20.00 >> u= [ 1 2 3]; v= [2 3 4]; >> u*v ??? Error using ==> mtimes Inner matrix dimensions must agree.
N
41
Dot . Product
The second way of forming the product of two vectors of the same length is known as the Hadamard product It is not often used in Mathematics but is an invaluable Matlab feature It involves vectors of the same type If u and v are two vectors of the same type (both row vectors or both column vectors), the mathematical definition of this product, which we shall call the dot product, is the vector having the components u . v = [u1v1, u2v2, ., unvn]: The result is a vector of the same length and type as u and v. Thus, we simply multiply the corresponding elements of two vectors Tabulate the function y = x sin(pi* x) for x = 0; 0:25; : : : ; 1.
>> u= [ 1 2 3]; v= [2 3 4]; >> u*v ??? Error using ==> mtimes Inner matrix dimensions must agree. >> u.*v ans = 2.00
42
43
4.00
9.00
256.00
6561.00
44
Multidimensional Arrays
>> r = randn(2,3,2) % create a 3 dimensional array filled %with normally distributed random numbers r=rand(2,3,2) r(:,:,1) = 0.2769 0.0971 0.6948 0.0462 0.8235 0.3171 randn(2,3,2): 3 dimensions, filled with normally distributed random numbers % sign precedes comments, MATLAB ignores the rest of the line
45
2D Matrix Manipulations
size(A) , max, min
>> a= [ 2 3 4; 2 a= 2.00 2.00 5.00 >> size(a) ans = 3.00 4 5; 5 6 7] 3.00 4.00 6.00 4.00 5.00 7.00
transpose(A), size(A)
>> a= [ 2 3 4; 2 a= 2.00 2.00 >> size(a) ans = 2.00 >> a' ans = 2.00 3.00 4.00 >> size(a') ans = 3.00 4 5] 3.00 4.00 4.00 5.00
3.00
3.00
diag(A)
>> diag(a) ans = 2.00 4.00 7.00
fliplr(A)
2.00
A=zeros(m,n)
zeros(2,4) ans = 0 0
eye(A)
>> eye(3) ans = 1.00 0 0 0 1.00 0 0 0 1.00
46
0 0
0 0
0 0
Matrix Manipulation
D=[1 2 3 4]; D=diag(1:4)
>> diag(1:4) ans = 1.00 0 0 0
F = [0 1 8 7; 3 -2 -4 2; 4 2 1 1] (non square matrix) What is diag(F)? Tabulate the functions y = 4 sin 3x and u = 3 sin 4x for x = 0, 0.1, 0.2,.,0.5. Given a matrix A = [ 1 2 3; 4 5 6; 5 6 7]; find the determinant of A; Adjoint of A; inverse of A; Find the inverse of matrix A = [ 1 2 3 4; 1 3 5 6; 5 4 3 2];
M S Ramaiah School of Advanced Studies
0 2.00 0 0
0 0 3.00 0
0 0 0 4.00
47
Matrix Manipulation
Given Matrix A = [1 2 3 4; 5 3 1 7; 2 7 9 4; 2 4 6 8]; Extract bits of A; extract locations of ( 8, 9 , 5, 1) Display the following Only row 3 Only row 4 Rows 2 and 4 Cols 1 and 3 Use the 4x 4 matrix concatenate it to make a 16x 16 Matrix Perform sum of diagonal elements
48
A*x
49
Sparse Matrix
Create a sparse 5x4 matrix S having only 3 non{zero values: S1,2 = 10, S3,3 = 11 and S5,4 =12.
>> m= [ 1 3 5]; >> n=[2 3 4]; >> v=[10 11 12]; >> A=sparse(m,n,v) A= (1,2) 10.00 (3,3) 11.00 (5,4) 12.00 >> A=full(A) A= 0 10.00 0 0 0 0 0 0 0 0
0
0 11.00 0 0 0
0
0 0 12.00
50
When A is non-singular and square (n x n), meaning that the number of independent equations is equal to the number of unknowns, the system has a unique solution given by x= A-1B
M S Ramaiah School of Advanced Studies
51
Example
Enter the symmetric coeffcient matrix and right hand side vector b given by
and solve the system of equations Ax = b using the three alternative methods: i) x = A-1b, (the inverse A-1 may be computed in Matlab using inv(A).) ii) x = A \ b, iii) xT = btAT leading to xT = b' / A which makes use of the slash or right division operator /. The required solution is then the transpose of the row vector xT.
M S Ramaiah School of Advanced Studies
52
Example
Use the backslash operator to solve the complex system of equations for which
53
Character Strings
close all; clear all; clc hi = ' hello'; class = 'MATLAB'; greetings = [hi class] vgreetings = [hi;class]
54
String Functions
yo = Hello Class >> ischar(yo) ans = 1 >> strcmp(yo,yo) ans = 1
returns 1 if string arguments are the same and 0 otherwise; strcmpi ignores case
55
Set Functions
Arrays are ordered sets:
>> a = [1 2 3 4 5] a = 1 2 3 >> b = [3 4 5 6 7] b = 3 4 5 >> isequal(a,b) ans = 0 >> ismember(a,b) ans = 0 0 1
7
returns true (1) if arrays are the same size and have the same values returns 1 where a is in b and 0 otherwise
56
Lab 1
Create a row vector called X whose elements are the integers 1 through 9. Create another row vector called Temp whose elements are: 15.6 17.5 36.6 43.8 58.2 61.6 64.2 70.4 98.8 These data are the result of an experiment on heat conduction through an iron bar. The array X contains positions on the bar where temperature measurements were made. The array Temp contains the corresponding temperatures. Make a 2-D plot with temperature on the y-axis and position on the x-axis. The data shown in your plot should lie along a straight line (according to physics) but dont because of measurement errors. Use the MATLAB polyfit function to fit the best line to the data (use >> hold on; for multiple plots in same figure). In other words use polyfit to determine the coefficients a and b of the equation T = ax + b Lastly, we can calculate a parameter called chi-square (2) that is a measure of how well the data fits the line. Calculate chi-square by running the MATLAB command that does the following matrix multiplication: >> (Temp-b-a*X)*(Temp-b-a*X)'
57
Lab 1
close all; clear all; clc; x=1:9; temp=[15.6 17.5 36.6 43.8 58.2 61.6 64.2 70.4 98.8]; p= polyfit(x,temp,1); T=p(1).*x+p(2); B=((temp-p(2)-p(1)).*x); Bd=((temp-p(2)-p(1)).*x)'; C=B*Bd; figure;plot(x,temp,'-*'); hold on; plot(x,T)
58
Lab 2
Write a MATLAB command that will generate a column vector called theta. theta should have values from 2 to 2 in steps of /100. Generate a matrix F that contains values of the following functions in the columns indicated: Column 1: cos() Column 2: cos(2)(1 + sin(2) Column 3: e -0.1|| Evaluate each of the above functions for the values in the theta vector from above. Plot each of the columns of F against theta. Overlay the three plots, using a different color for each. Create a new column vector called maxVect that contains the largest of the three functions above for each theta. Plot maxVect against theta. Create a column vector called maxIndex that has the column number of the maximum value in that row.
59
Lab 3
Mesh and Contour plots
close all; clear all; clc; [X,Y] = meshgrid(2:.2:4, 1:.2:3); f =-X.*Y.*exp(-2*(X.^2+Y.^2)); figure(1); mesh(X,Y,f), xlabel('x'), ylabel('y'), grid figure (2), contour(X,Y,f) xlabel('x'), ylabel('y'), grid, hold on fmax = max(max(f)); kmax = find(f==fmax); Pos = [X(kmax), Y(kmax)]; plot(X(kmax),Y(kmax),'*') text(X(kmax),Y(kmax),' Maximum')
60
Programming
61
Outline
MATLAB m-file Editor To start: click icon or enter edit command in Command Window, e.g., >> edit test.m Scripts and Functions Decision Making/Looping if/else switch for and while Running Operating System Commands
62
You can save and run the file/function/script in one step by clicking here
Tip: semi-colons suppress printing, commas (and semi-colons) allow multiple commands on one line, and 3 dots () allow continuation of lines without execution
63
64
>> myfun(2,3) % called with zero outputs ans = 100 >> u = myfun(2,3) % called with one output u = 100 >> [u v w] = myfun(2,3) % called with all outputs u = 100 v = Any return value which is not stored 6 in an output variable is simply w = discarded 4
65
Fibonacci
function f = fibonacci(n) % FIBONACCI Fibonacci sequence % f = FIBONACCI(n) generates the first n Fibonacci numbers. f = zeros(n,1); f(1) = 1; f(2) = 2; for k = 3:n f(k) = f(k-1) + f(k-2); end
66
Sum
Produce a list of the values of the sums
close all; clear all; clc x=1:20; s(20)=sum(1./(x.^2)); for j= 21:100 s(j)=s(j-1)+(1./(j^2)); end s
M S Ramaiah School of Advanced Studies
67
68
X [k ] x[n]e
N 1
1 x[n] X [k ]e N k 0
M S Ramaiah School of Advanced Studies
j 2 kn N
69
11
0
After fftshift
N=11
70
71
72
Frequency Spectrum
73
Area
74
75
76
if/elseif/else Statement
>> A = 2; B = 3; >> if A > B 'A is bigger' elseif A < B 'B is bigger' elseif A == B 'A equals B' else error('Something odd is happening') end ans = B is bigger
77
switch Statement
>> n = 8 n = 8 >> switch(rem(n,3)) case 0 m = 'no remainder' case 1 m = the remainder is one' case 2 m = the remainder is two' otherwise error('not possible') end m = the remainder is two
78
for Loop
>> for i = 2:5 for j = 3:6 a(i,j) = (i + j)^2 end end >> a a = 0 0 0 0 0 0 0 25 36 49 0 0 36 49 64 0 0 49 64 81 0 0 64 81 100
0 64 81 100 121
79
A Performance Tip
Input variables are not copied into the function workspace, unless
If any input variables are changed, the variable will be copied
Avoid performance penalty when using large arrays by extracting only those elements that will need modification
80
81
c:\ E:\MATLAB\R2006b\work E:\MATLAB\R2006b\work E:\MATLAB\R2006b\work\f_funcs E:\MATLAB\R2006b\work\f_funcs E:\MATLAB\R2006b\work\na_funcs E:\MATLAB\R2006b\work\na_funcs E:\MATLAB\R2006b\work\na_scripts E:\MATLAB\R2006b\toolbox\matlab\genera E:\MATLAB\R2006b\work\na_scripts l E:\MATLAB\R2006b\toolbox\matlab\general E:\MATLAB\R2006b\toolbox\matlab\ops E:\MATLAB\R2006b\toolbox\matlab\ops
Lab 1
Create, perhaps using for-loops, a synthetic image that has a 1 in the (1,1) location, and a 255 in the (128,128) location, and i + j - 1 in the i, j location. This we'll refer to as the diagonal gray'' image. Can you manage to do this without using for-loops? Display the image using (well assume you placed your image in a matrix named a) image(a); colormap(gray). (Dont worry if this doesnt work exactly the way you expect. Colormaps can be tricky!) Now convert your code to a MATLAB script Test your script to insure that it produces the same results as the ones obtained interactively.
83
Lab 2
Write a MATLAB function that implements Newtons iterative algorithm for approximating the square root of a number. The core of Newtons algorithm is that if last is the last approximation calculated, the next (improved) approximation is given by next = 0.5(last +(x/last)) where x is the number whose square root you seek. Two other pieces of information are needed to implement the algorithm. The first is an initial guess at the square root. (A typical starting value might be 1.0, say). The second is the accuracy required for the approximation. You might specify you want to keep iterating until you get an approximation that is good to 5 decimal places for example. Your MATLAB function should have three input arguments: x, the initial guess, and the accuracy desired. It should have one output, the approximate square root of x to the desired accuracy.
84
Data I/O
85
86
87
dlmwrite dlmwrite(filename,A,delimiter); writes ASCII values in array A to file filename with values separated by delimiter
Useful with spreadsheet data
88
specify values for whitespace, delimiters and exponent characters specify a format string to skip over literals or ignore fields
89
textread Example
Data file, tab delimited:
MATLAB m-file:
Results:
Import Wizard
Import ASCII and binary files using the Import Wizard. Type uiimport at the Command line or choose Import Data from the File menu.
91
File Opening and Closing fclose: Close one or more open files fopen: Open a file or obtain information about open files Unformatted I/O fread: Read binary data from file fwrite: Write binary data to a file Formatted I/O fgetl: Return the next line of a file as a string without line terminator(s) fgets: Return the next line of a file as a string with line terminator(s) fprintf: Write formatted data to file fscanf: Read formatted data from file
92
feof: Test for end-of-file ferror: Query MATLAB about errors in file input or output frewind: Rewind an open file fseek: Set file position indicator ftell: Get file position indicator
String Conversion
sprintf: Write formatted data to a string sscanf: Read string under format control
93
Name of file
status = fclose(fid);
94
Formatted I/O
fscanf: [A, count] = fscanf(fid,format,size); Number successfully read File identifier number Format specifier Amount of data to read: n, [n, m], Inf
Data array
Format specifier
95
%-12.5e
initial % character alignment flag width and precision conversion specifier
Specifier Description %c Single character %d Decimal notation (signed) %e Exponential notation %f Fixed-point notation %g The more compact of %e or %f %o Octal notation (unsigned) %s String of characters %u Decimal notation (unsigned) %x Hexadecimal notation ...others...
96
97
int, double,
99
10 0
Each column is the raw rpm sensor data from a different sensor used in an instrumented engine test. The rows represent the times readings were made.
10 1
Note that in this case the plot command generates one timeseries for each column of the data matrix
10 2
Applying the mean function to the data matrix yields the mean of each column
2
>> mean(rpm_raw)
ans = 1081.4 1002.7
1082.8
But you can easily compute the mean of the entire matrix (applying a function to either a single row or a single column results in the function applied to the column, or the row, i.e., in both cases, the application is to the vector).
>> mean(mean(rpm_raw))
ans =
1055.6
10 3
3
So we can easily obtain the row means
10 4
1043
10 5
min
>> min(rpm_raw) ans = 1053
min along each column
1053
961
min of entire matrix
961
10 6
10 8
Histogram (cont.)
>> hist(rpm_raw) %histogram of the data
10 9
Histogram (cont.)
>> hist(rpm_raw, 20) %histogram of the data
11 0
Histogram (cont.)
>> hist(rpm_raw, 100) %histogram of the data
11 1
This example uses an FIR filter to compute a moving average using a window size of 3
11 2
11 3
fc1= 0.5; % cut off frequency n1=2;% order of filter wn1=(2*fc1/fs); [b1,a1] = butter(n1,wn1,'high'); h1=filter(b1,a1,ecg); figure(5); plot(h1); xlabel('no. of samples'); title('High pass filtered ECG at 0.5Hz'); ylabel('Amplitude in mV'); figure(6) freqz(b1,a1); title('High Pass Filter characteristics');
11 4
h2 = filter(b2,a2,h1); % notch filter figure(8); plot(h2) xlabel('no. of samples'); title('Notch filtered ECG at 60 Hz'); ylabel('Amplitude in mV '); figure(9); freqz(b2,a2); title('Notch Filter characteristics'); % frequency domain raw_fft2= fft(h2,fft_samples); f_axis2= 0:1:(fft_samples-1)/2; % fft_samples -1 because we start at 0 avg_power2 = sum(abs(raw_fft2(1:fft_samples/2)).^2./slen)/slen; figure(10); plot( f_axis2*fs/fft_samples, ... abs(raw_fft2(1:fft_samples/2))*2/slen,f_axis2*fs/fft _samples,avg_power2); title('Notch filtered signal Frequency Domain'); ylabel('Magnitude [Normalized]'); xlabel('Frequency [Hz]');
% Notch filter coefficient b0 = (abs(1-2*r*cos(Theta0)+r^2))/(2*abs(1-cos(Theta0))); b2 = [b0 (b0*(-2)*cos(Theta0)) b0]; % Numerator coefficients for filter a2 = [1 (-2*r*cos(Theta0)) r^2]; % Denominator coefficients for filter
11 5
% frequency domain
raw_fft3= fft(h3,fft_samples); f_axis3= 0:1:(fft_samples-1)/2; % fft_samples -1 because we start at 0 avg_power3 = sum(abs(raw_fft3(1:fft_samples/2)).^2./slen)/slen; figure(13); plot( f_axis3*fs/fft_samples, ... abs(raw_fft3(1:fft_samples/2))*2/slen,f_axis3*fs/fft_samples,avg_power3); title('Low pass filtered signal Frequency Domain'); ylabel('Magnitude [Normalized]'); xlabel('Frequency [Hz]'); % 1 epoch figure(1) subplot(4,1,1); plot(ecg(1:800));xlabel('samples');ylabel('Amplitude in mV');title('raw ECG'); subplot(4,1,2); plot(h1(1:800));xlabel('samples');;ylabel('Amplitude in mV');title('HPF ECG'); subplot(4,1,3); plot(h2(1:800));xlabel('samples');ylabel('Amplitude in mV');title('Notch ECG'); subplot(4,1,4); plot(h3(1:800));xlabel('samples');ylabel('Amplitude in mV');title('LPF ECG');
11 6
Lab 1
Load the data_analysis_lab1.mat file into the MATLAB workspace. This will produce an array variable called grades containing grades on an exam between 0 and 100. Calculate the average and standard deviation of the grades. Plot a histogram of the grades using 100 bins. We want to compare the histogram with a Gaussian distribution. Write you own MATLAB Gaussian function M-file which returns a value y using the following formula y=exp(-[x-m]2/22) where m is the average and is the standard deviation of the distribution. Your function should have input arguments x,m, and . On the histogram plot also plot a Gaussian distribution of the grades using the calculated average and standard deviation.
11 7
Lab 2
Load the file data_analysis_lab2.mat. Since this is a .mat file, you should be able to load it easily using the load command. Your workspace should now contain a single variable x. x is 3000 points long and consists of the sum of 3 sine waves. The sampling frequency is 1000 Hz. Plot the first 0.33 seconds of x. You may find it convenient to create a second array (say called time) that has the time values corresponding to the samples in x. >> Fs = 1000; %Sampling frequency >> time = [0:length(x)-1]*(1/Fs); % time index fft is a built-in function in MATLAB. We can compute and plot the magnitude of the FFT of x to identify the frequencies of the sine waves. >> X = fft(x); X is a complex valued array that is the FFT of x. We can compute the magnitude of the FFT by taking the absolute value of X. >> Xmag = abs(X); >> plot(Xmag);
11 8
Lab 2 (cont.)
The plot of Xmag shows 6 components, and also we have only index values not real frequency values along the abscissa. Six components show up because the FFT is evaluated over positive and negative frequencies. Also, the frequencies are wrapped around. We can take care of the wrap around using the fftshift function. >> Xmag = fftshift(Xmag); Next, we can generate a suitable frequency axis for plotting Xmag. >> frq = [0:length(Xmag)-1]*(Fs/length(Xmag)) (Fs/2); >> plot(frq, Xmag); Can you see the 3 frequency components (in the positive freq. part of the axis)? Zoom into the plot either using the axis command or the interactive zoom button on the figures toolbar and determine the frequencies of the 3 components.
11 9
Matrix Factorizations: lu
lu: factors a square matrix A into the product of a permuted lower triangular matrix L and an upper triangular matrix U such that A = LU. Useful in computing inverses, Gaussian elimination.
>> A = [1 2 -1; 1 0 1; -1 2 1]; >> [L, U] = lu(A) L = 1 0 0 1 -0.5 1 -1 1 0 U = 1 2 -1 0 4 0 0 0 2 >> L * U ans = 1 2 -1 1 0 1 -1 2 1
[V,D] = eig(A) returns the eigenvectors of A in the columns of V, and the eigenvalues in the diagonal elements of D.
0.46499 -0.93577 -0.052149 0.34874 S = 6.4999 0 0 1.3235 0 0 V = -0.98447 -0.17558 0.17558 -0.98447
Pseudoinverse: pinv
pinv: The pseudoinverse of an n x m matrix A is a matrix B such that BAB = B and ABA = A
>> A = [2 -1; 1 1; 6 -1]; >> B = pinv(A) B = -0.013514 0.13514 0.14865 -0.36486 0.64865 0.013514 >> A*B*A ans = 2 -1 1 1 6 -1 >> B*A*B ans = -0.013514 0.13514 0.14865 -0.36486 0.64865 0.013514
Numerical Integration
trapz: Trapezoidal integration
quad: Adaptive, recursive Simpsons Rule for quadrature quadl: Adaptive, recursive Newton-Coates
8-panel rule
12 6
12 7
p(x)=x3+4x2-7x-10
12 8
12 9
13 0
Lab 1
Consider the set of equations Ax=b where A is an 8x8 matrix given by A(i,j)=1.0+(|i-j|/8.0) and b is a 8x1 array given by b(i)=i Solve for x using: The \ operator The MATLAB pinv function The MATLAB inv function LU Decomposition How do your answers compare? For best performance, evaluate the matrix A without using any for loops
13 1
Lab 2
Use numerical integration to integrate 1/(1+x2) from 0 to 1. The result is analytically calculated to be /4. Use the following three MATLAB functions: trap() quad() quadl()
and compare the accuracy of your numerical result with the exact value. Use quad or quadl to get the most accurate result possible with MATLAB. How accurate is it?
13 2
Tool boxes
Signal and Image processing Audio processing wavread aviread
13 3
WAV READ
close all; clear all; clc %%%%%%%%%%%%%%%%%%% READ SIGNAL [s, fs, nbits, readinfo] = wavread('ak47-1.wav'); s=s(:,1)'; L=length(s); t=1:L; t=t/fs; figure; plot(t,s) s1=s+awgn(s,10); figure; plot(t,s1) % xlabel('time in seconds'); % ylabel('Amplitude'); % title('AK47 Signal'); N=1024; X = fft(s,N); F=fs*linspace(0,1,N); figure;plot(F(1:N/2),abs(X(1:N/2))); xlim([0 2000]); title('raw signal') X1 = fft(s1,N); F=fs*linspace(0,1,N); figure;plot(F(1:N/2),abs(X1(1:N/2))); xlim([0 2000]); title('noisy signal') % xlabel('frequency'); % ylabel('Magnitude'); % title('FFT of input AK47 Signal');
13 4
AVI READ
clc; clear all; close all; %----------------Inputs--------------------video = '7.avi'; Frm = 17;
%--------Reading Frame from Video----------a = aviread(video,Frm) im5 = a.cdata; a = aviread(video,Frm+1) im6 = a.cdata; %--------Converting Grey Scale----------im3=rgb2gray(im5); im4=rgb2gray(im6); %----------1 st Level Pyramid----------im3=impyramid(im3,'reduce'); im4=impyramid(im4,'reduce'); %----------2 nd Level Pyramid----------im3=impyramid(im3,'reduce'); im4=impyramid(im4,'reduce'); figure; imshow(im3) figure;imshow(im4)
13 5
Thank You
13 6