You are on page 1of 136

Introduction to MATLAB

Preetham Shankpal Asst. Professor, M S Ramaiah School of Advanced Studies Email: preetham@msrsas.org

M S Ramaiah School of Advanced Studies

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

Widely used in engineering, mathematics, and science


It has packages with specialized functions
M S Ramaiah School of Advanced Studies

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

M S Ramaiah School of Advanced Studies

Toolboxes, Software, & Links

M S Ramaiah School of Advanced Studies

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

M S Ramaiah School of Advanced Studies

Online MATLAB Resources


www.mathworks.com/ www.mathtools.net/MATLAB www.math.utah.edu/lab/ms/matlab/matlab.html web.mit.edu/afs/athena.mit.edu/software/matlab/ www/home.html www.utexas.edu/its/rc/tutorials/matlab/ www.math.ufl.edu/help/matlab-tutorial/ www.indiana.edu/~statmath/math/matlab/links.html www-h.eng.cam.ac.uk/help/tpl/programs/matlab.html

M S Ramaiah School of Advanced Studies

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.

M S Ramaiah School of Advanced Studies

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

M S Ramaiah School of Advanced Studies

Some MATLAB Development Windows


Command Window: where you enter commands Command History: running history of commands which is preserved across MATLAB sessions Current directory: Default is $matlabroot/work Workspace: GUI for viewing, loading and saving MATLAB variables Array Editor: GUI for viewing and/or modifying contents of MATLAB variables (openvar varname or double-click the arrays name in the Workspace) Editor/Debugger: text editor, debugger; editor works with file types in addition to .m (MATLAB m-files)

M S Ramaiah School of Advanced Studies

MATLAB Editor Window

M S Ramaiah School of Advanced Studies

10

MATLAB Help Window (Very Powerful)

M S Ramaiah School of Advanced Studies

11

Command-Line Help : List of Topic Functions


>> help matfun Matrix functions - numerical linear algebra.

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.

M S Ramaiah School of Advanced Studies

12

Keyword Search of Help Entries


>> lookfor who newton.m: % inputs: 'x' is the number whose square root we seek testNewton.m: % inputs: 'x' is the number whose square root we seek WHO List current variables. WHOS List current variables, long form. TIMESTWO S-function whose output is two times its input.

>> whos Name ans fid i

Size 1x1 1x1 1x1

Bytes 8 8 8

Class double double double

Attributes

M S Ramaiah School of Advanced Studies

13

Variables (Arrays) and Operators

M S Ramaiah School of Advanced Studies

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

M S Ramaiah School of Advanced Studies

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

M S Ramaiah School of Advanced Studies

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

mixed data types

semi-colon suppresses output of the calculations result

M S Ramaiah School of Advanced Studies

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

M S Ramaiah School of Advanced Studies

18

Numbers & Formats


Matlab recognizes several different kinds of numbers

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

Numbers & Formats


Type help format for full list. Should you wish to switch back to the default format then format will suffice. The command format compact is also useful in that it suppresses blank lines in the output thus allowing more information to be displayed

M S Ramaiah School of Advanced Studies

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

M S Ramaiah School of Advanced Studies

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

complex numbers (i or j) require no special handling

save/load are used to

retain/restore workspace variables

M S Ramaiah School of Advanced Studies

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

M S Ramaiah School of Advanced Studies

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

M S Ramaiah School of Advanced Studies

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

>> pi/6 ans = 0.52


25

M S Ramaiah School of Advanced Studies

Other Elementary Functions


These include sqrt, exp, log, log10
>> x = 9; sqrt(x),exp(x),log(sqrt(x)),log10(x^2+6) ans = 3.00 ans = 8103.08 ans = 1.10 ans = 1.94

M S Ramaiah School of Advanced Studies

26

Vectors Rows and Columns


Row Vectors They are lists of numbers separated by either commas or spaces. The number of entries is known as the length of the vector and the entries are often referred to as elements or components of the vector The entries must be enclosed in square brackets
>> v = [ 1 3, sqrt(5)] v= 1.00 3.00 >> length(v) ans = 3.00

2.24 >> v2 = [3+ 4 5] v2 = 7.00 5.00 >> v2 = [3 +4 5] v2 = 3.00 4.00

Spaces can be vitally important:

5.00
27

M S Ramaiah School of Advanced Studies

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

3.00 4.00 7.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

The error is due to v and v2 having different lengths

M S Ramaiah School of Advanced Studies

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

We can build row vectors from existing ones:


>> w = [1 2 3], z = [8 9] cd = [2*z,-w], sort(cd) w= 1.00 2.00 z= 8.00 9.00 cd = 16.00 18.00 ans = -3.00 -2.00

3.00

-1.00 -1.00

-2.00 16.00

-3.00 18.00
29

M S Ramaiah School of Advanced Studies

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

M S Ramaiah School of Advanced Studies

30

The Colon Notation


This is a shortcut for producing row vectors:
lower limit Upper limit

>> 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

>> 1:3:7 ans = 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

Extracting Bits of a Vector


To get the 3rd to 6th entries:
>> r5 = [1:2:6, -1:-2:-7] r5 = 1.00 3.00 >> r5(3:6) ans = 5.00 -1.00

5.00

-1.00

-3.00

-5.00

-7.00

-3.00

-5.00

To get alternate entries


>> r5(1:2:7) ans = 1.00

5.00

-3.00

-7.00

What does r5(-6:2:1) give?


>> r5(6:-2:1) ans = -5.00

-1.00

3.00
32

M S Ramaiah School of Advanced Studies

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

>> c= 2*a -3*b c= -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

>> a' ans =


1.00 2.00 3.00 >> c= [ 2; 3; 4] c= 2.00 3.00 4.00 >> d= a'+(3*c) d= 7.00 11.00 15.00

If x is a complex vector, then x' gives the complex conjugate transpose of x:


a=[1-1i 1+1i]; b=a'; 1.00 - 1.00i 1.00+1.00i 1.00 + 1.00i 1.00 - 1.00i
34

M S Ramaiah School of Advanced Studies

Plotting Elementary Functions


3

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

xlabel ylabel title grid figure

-1

-2

-3

0.01

0.02

0.03

0.04

0.05

0.06

0.07

M S Ramaiah School of Advanced Studies

35

Multiple Plots
3

plot(t,sin(wt), t,cos(wt))

-1

-2

xlabel ylabel title hold on subplot Data cursor (marker)

-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

M S Ramaiah School of Advanced Studies

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.

tic; x=0.1:0.001:200; y=besselj(3,x) + log(x); toc; Elapsed time is 0.551970 seconds.

Roughly 31 times faster without use of for loop

M S Ramaiah School of Advanced Studies

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

3.00 4.00 5.00

2.00 3.00 4.00

M=magic(4)

M S Ramaiah School of Advanced Studies

38

Matrices: Magic Squares


This matrix is called a magic square

Interestingly, Durer also dated this engraving by placing 15 and 14 side-byside in the magic square.

M S Ramaiah School of Advanced Studies

39

Durer Magic Square


>> M=magic(4); >> [b]=[sum(M(1,:)) sum(M(2,:)) sum(M(3,:)) sum(M(4,:))] >>[c]=[sum(M(:,1)) sum(M(:,2)) sum(M(:,3)) sum(M(:,4))]

M S Ramaiah School of Advanced Studies

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

(row vector x column vector)

(row vector x column vector)

an error results because w is not a column vector


M S Ramaiah School of Advanced Studies

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

plot(x,y) 6.00 12.00


M S Ramaiah School of Advanced Studies

42

Dot Division of Arrays (./)


There is no mathematical definition for the division of one vector by another. However, in Matlab, the operator ./ is defined to give element by element division it is therefore only defined for vectors of the same size and type
>> a=[1 2 3]; >> b=[1 2 3]; >> c=a/b c= 1.00 >> c=a./b c= 1.00 1.00 1.00 >> a=[12 24 36];b=[6 3 9]; >> c=a/b c= 3.71 >> c=a./b c= 2.00 8.00 4.00
M S Ramaiah School of Advanced Studies

43

Dot Power of Arrays (.^)


To square each of the elements of a vector we could, for example, do u.*u. However, a neater way is to use the .^ operator
>> a=[ 1 2 3]; >> a=a.^2 a= 1.00 a= 1.00 >> a=a.^4 a= 1.00 4.00 9.00

4.00

9.00

Draw plots for the following

256.00

6561.00

M S Ramaiah School of Advanced Studies

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

r(:,:,2) = 0.9502 0.4387 0.7655 0.0344 0.3816 0.7952

M S Ramaiah School of Advanced Studies

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 4.00 5.00

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

M S Ramaiah School of Advanced Studies

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

M S Ramaiah School of Advanced Studies

48

Dot product of matrices (.*)


The dot product works as for vectors: corresponding elements are multiplied together so the matrices involved must have the same size
>> A= [ 1 2 3 4; 3 4 5 6; 6 7 8 9]; >> B= [ 2 3 4 5; 5 6 7 7; 8 9 3 4]; >> A*B ??? Error using ==> mtimes Inner matrix dimensions must agree. >> A.*B ans = 2.00 15.00 48.00

6.00 24.00 63.00

12.00 35.00 24.00

20.00 42.00 36.00

A*x

M S Ramaiah School of Advanced Studies

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

M S Ramaiah School of Advanced Studies

Systems of Linear Equations


Mathematical formulations of engineering problems often lead to sets of simultaneous linear equations. Such is the case, for instance, when using the finite element method (FEM). A general system of linear equations can be expressed in terms of a coefficient matrix A, a right-hand-side (column) vector b and an unknown (column) vector x as Ax=b

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

M S Ramaiah School of Advanced Studies

53

Character Strings
close all; clear all; clc hi = ' hello'; class = 'MATLAB'; greetings = [hi class] vgreetings = [hi;class]

concatenation with blank or with , semi-colon: join vertically

M S Ramaiah School of Advanced Studies

54

String Functions
yo = Hello Class >> ischar(yo) ans = 1 >> strcmp(yo,yo) ans = 1

returns 1 if argument is a character array and 0 otherwise

returns 1 if string arguments are the same and 0 otherwise; strcmpi ignores case

M S Ramaiah School of Advanced Studies

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

M S Ramaiah School of Advanced Studies

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)'

M S Ramaiah School of Advanced Studies

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)

M S Ramaiah School of Advanced Studies

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.

M S Ramaiah School of Advanced Studies

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')

M S Ramaiah School of Advanced Studies

60

Programming

M S Ramaiah School of Advanced Studies

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

M S Ramaiah School of Advanced Studies

62

m-file Editor Window

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

M S Ramaiah School of Advanced Studies

63

Scripts and Functions


Scripts do not accept input arguments, nor do they produce output arguments. Scripts are simply MATLAB commands written into a file. They operate on the existing workspace. Functions accept input arguments and produce output variables. All internal variables are local to the function and commands operate on the function workspace. A file containing a script or function is called an m-file If duplicate functions (names) exist, the first in the search path (from path command) is executed.

M S Ramaiah School of Advanced Studies

64

Functions First Example


function [a b c] = myfun(x, y) Write these two lines to a file b = x * y; a = 100; c = x.^2; myfun.m and save it on MATLABs path

>> 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

M S Ramaiah School of Advanced Studies

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

M S Ramaiah School of Advanced Studies

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

Fast Fourier Transform (FFT)


fft is one of the built-in functions in MATLAB The fft function can compute the discrete Fourier transform of any arbitrary length sequence. fft incorporates most known fast algorithms for various lengths (e.g. power of 2) Not all lengths are equally fast

M S Ramaiah School of Advanced Studies

68

Discrete Fourier Transform Definition


N 1 n0 j 2 kn N

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

fft and fftshift


1
N=11

11

0
After fftshift

N=11

M S Ramaiah School of Advanced Studies

70

Example: FFT of sine Wave in Noise


>> >> >> >> >> >> >> >> >> fs = 1000; t = [0:999]*(1/fs); x = sin(2*pi*250*t); X = fft(x(1:512)); noise = 0.8*randn(size(x)); xn = x + noise; XnMag = fftshift(20*log10(abs(fft(xn(1:512))))); XnMagPf = XnMag(256:512); frq = [0:length(XnMagPf) 1]'*(fs/length(XnMag)); >> plot(frq, XnMagPf) >> xlabel('freq. (Hz)'); >> ylabel('Mag. (db)');

M S Ramaiah School of Advanced Studies

71

Develop code for FFT


function [ F Fr] = FCFT(fo,fl,x,fint,fs) i=1; for fr=fo:fint:fl w=2*pi*fr;u=1; for t=0:1/fs:0.5 X(u)=x(u)*exp(-1i*w*t); u=u+1; end N = length(X); F(i) = simp(X,N,1/fs); i = i + 1; end Fr = fo:fint:fl; end
M S Ramaiah School of Advanced Studies

72

Frequency Spectrum

M S Ramaiah School of Advanced Studies

73

Area

function [A] = area(a,b,c) s = (a+b+c)/2; A = sqrt(s*(s-a)*(s-b)*(s-c));

M S Ramaiah School of Advanced Studies

74

Function Syntax Summary


If the m-file name and function name differ, the file name takes precedence Function names must begin with a letter First line must contain function followed by the most general calling syntax Statements after initial contiguous comments (help lines) are the body of the function

Terminates on the last line or a return statement

M S Ramaiah School of Advanced Studies

75

Function Syntax Summary (cont.)


error and warning can be used to test and continue execution (error-handling)

Scripts called in m-file functions are evaluated in the function workspace


Additional functions (subfunctions) can be included in an m-file Use which command to determine precedence, e.g., >> which title C:\MATLAB71\toolbox\matlab\graph2d\title

M S Ramaiah School of Advanced Studies

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

M S Ramaiah School of Advanced Studies

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

M S Ramaiah School of Advanced Studies

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

M S Ramaiah School of Advanced Studies

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

M S Ramaiah School of Advanced Studies

80

MATLABs Search Path


Is name a variable?
Is name a built-in function? Does name exist in the current directory? Does name exist anywhere in the search path? Discovery functions: who, whos, what, which, exist, help, doc, lookfor, dir, ls, ...

M S Ramaiah School of Advanced Studies

81

Changing the Search Path


The addpath command adds directories to the MATLAB search path. The specified directories are added to the beginning of the search path.
>> path
MATLABPATH

>> addpath('c:\'); >> matlabpath


MATLABPATH

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

rmpath is used to remove paths from the search path

M S Ramaiah School of Advanced Studies

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.

M S Ramaiah School of Advanced Studies

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.

M S Ramaiah School of Advanced Studies

84

Data I/O

M S Ramaiah School of Advanced Studies

85

Loading and Saving Workspace Variables


MATLAB can load and save data in .MAT format .MAT files are binary files that can be transferred across platforms; as much accuracy as possible is preserved. Load: load filename OR A = load(filename) loads all the variables in the specified file (the default name is MATLAB.MAT) Save: save filename variables saves the specified variables (all variables by default) in the specified file (the default name is MATLAB.MAT)

M S Ramaiah School of Advanced Studies

86

ASCII File Read/Write


load and save can also read and write ASCII files with rows of space separated values: load test.dat ascii save filename variables (options are ascii, double, tabs, append) save example.dat myvar1 myvar2 -ascii -double

M S Ramaiah School of Advanced Studies

87

ASCII File Read/Write (cont.)


dlmread M = dlmread(filename,delimiter,range); reads ASCII values in file filename that are separated by delimiter into variable M; most useful for numerical values. The last value in a line need not have the delimiter following it. range = [R1 C1 R2 C2] (upper-left to lower-right corner)

dlmwrite dlmwrite(filename,A,delimiter); writes ASCII values in array A to file filename with values separated by delimiter
Useful with spreadsheet data

range of data to be read

M S Ramaiah School of Advanced Studies

88

More ASCII File Read


textread [A, B, C, ...] = textread[filename, format]; [A, B, C, ...] = textread[filename, format, N]; [...] = textread[..., param, value, ...]; The type of each return argument is given by format (C-style conversion specifiers: %d, %f, %c, %s, etc) Number of return arguments must match number of conversion specifiers in format format string is reused N times or entire file is read if N not given Using textread you can

specify values for whitespace, delimiters and exponent characters specify a format string to skip over literals or ignore fields

M S Ramaiah School of Advanced Studies

89

textread Example
Data file, tab delimited:

MATLAB m-file:

param,value pairs use doc textread for available param options

Results:

M S Ramaiah School of Advanced Studies

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.

M S Ramaiah School of Advanced Studies

91

Low-Level File I/O Functions

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

M S Ramaiah School of Advanced Studies

92

Low-Level File I/O (cont.)


File Positioning

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

M S Ramaiah School of Advanced Studies

93

File Open (fopen)/Close (fclose)


fid = fopen(filename, permission);
Permission requested: r, r+ w, w+ a, a+

File identifier number

Name of file

status = fclose(fid);

0, if successful -1, otherwise

File identifier number or all for all files

M S Ramaiah School of Advanced Studies

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

fprintf: count = fprintf(fid, format, A,...);

Number successfully read

File identifier number

Format specifier

Data array(s) to write

fscanf and fprintf are similar to C version but vectorized

M S Ramaiah School of Advanced Studies

95

Format String Specification

%-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...

M S Ramaiah School of Advanced Studies

96

Other Formatted I/O Commands


fgetl: line = fgetl(fid); reads next line from file without line terminator fgets: line = fgets(fid); reads next line from file with line terminator textread: [A,B,C,...] = textread('filename','format',N) reads N lines of formatted text from file filename sscanf: A = sscanf(s, format, size); reads string under format control sprintf: s = sprintf(format, A); writes formatted data to a string

M S Ramaiah School of Advanced Studies

97

Binary File I/O


[data, count] = fread(fid, num, precision);
Data array Number successfully read File identifier number Amount to read n, [n, m],... int, double,

count = fwrite(fid, data, precision);


Number successfully written File identifier number array to write

int, double,

fread and fwrite are vectorized


98

M S Ramaiah School of Advanced Studies

Basic Data Analysis

M S Ramaiah School of Advanced Studies

99

Basic Data Analysis


Basic, and more advanced, statistical analysis is easily accomplished in MATLAB. Remember that the MATLAB default is to assume vectors are columnar. Each column is a variable, and each row is an observation.

M S Ramaiah School of Advanced Studies

10 0

Vibration Sensors Data

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.

M S Ramaiah School of Advanced Studies

10 1

Plotting the Data


>> >> >> >> plot(rpm_raw) xlabel('sample number - during time slice'); ylabel('Unfiltered RPM Data'); title(3 sequences of samples from RPM sensor)

Note that in this case the plot command generates one timeseries for each column of the data matrix

M S Ramaiah School of Advanced Studies

10 2

Average of the Data:


1

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

M S Ramaiah School of Advanced Studies

10 3

The mean Function


>> help mean MEAN Average or mean value. For vectors, MEAN(X) is the mean value of the elements in X. For matrices, MEAN(X) is a row vector containing the mean value of each column. For N-D arrays, MEAN(X) is the mean value of the elements along the first non-singleton dimension of X. MEAN(X,DIM) takes the mean along the dimension DIM of X. Example: If X = [0 1 2 3 4 5] then mean(X,1) >> mean(rpm_raw, ans = 1045.7 1064.7 1060.7 1055 1045

But we can apply the mean function along any dimension

is [1.5 2.5 3.5] and mean(X,2) is [1 2) 4]

3
So we can easily obtain the row means

M S Ramaiah School of Advanced Studies

10 4

max and its Index


1
MAX Largest component. For vectors, MAX(X) is the largest element in X. For matrices, MAX(X) is a row vector containing the maximum element from each column. For N-D arrays, MAX(X) operates along the first non-singleton dimension. [Y,I] = MAX(X) returns the indices of the maximum values in vector I. If the values along the first nonsingleton dimension contain more than one maximal element, the index of the first one is returned.

2 >> max(rpm_raw) ans = 1115 1120

1043

>> max(max(rpm_raw)) ans = 1120


>> [y,i] = max(rpm_raw) y = 1115 1120 1043 i = 8 2 17
max along the columns

We can compute the max of the entire matrix, or of any dimension

M S Ramaiah School of Advanced Studies

10 5

min
>> min(rpm_raw) ans = 1053
min along each column

1053

961
min of entire matrix

>> min(min(rpm_raw)) ans = 961 >> [y,i] = min(rpm_raw) y = 1053 1053 i = 22 1 22

961

M S Ramaiah School of Advanced Studies

10 6

Standard Deviation, Median, Covariance


>> median(rpm_raw) % median along each column ans = 1080 1083.5 1004 >> cov(rpm_raw) % covariance of the data ans = 306.4 -34.76 32.192 -34.76 244.9 -165.21 32.192 -165.21 356.25 >> std(rpm_raw) % standard deviation along each column ans = 17.504 15.649 18.875 >> var(rpm_raw) % variance is the square of std ans = 306.4 244.9 356.25
10 7

M S Ramaiah School of Advanced Studies

Data Analysis: Histogram


HIST Histogram. N = HIST(Y) bins the elements of Y into 10 equally spaced containers and returns the number of elements in each container. If Y is a matrix, HIST works down the columns. N = HIST(Y,M), where M is a scalar, uses M bins.
N = HIST(Y,X), where X is a vector, returns the distribution of Y among bins with centers specified by X. The first bin includes data between -inf and the first center and the last bin includes data between the last bin and inf. Note: Use HISTC if it is more natural to specify bin edges instead. ...

M S Ramaiah School of Advanced Studies

10 8

Histogram (cont.)
>> hist(rpm_raw) %histogram of the data

M S Ramaiah School of Advanced Studies

10 9

Histogram (cont.)
>> hist(rpm_raw, 20) %histogram of the data

M S Ramaiah School of Advanced Studies

11 0

Histogram (cont.)
>> hist(rpm_raw, 100) %histogram of the data

M S Ramaiah School of Advanced Studies

11 1

Bin Average Filtering


FILTER One-dimensional digital filter. Y = FILTER(B,A,X) filters the data in vector X with the filter described by vectors A and B to create the filtered data Y. The filter is a "Direct Form II Transposed" implementation of the standard difference equation: a(1)*y(n) = b(1)*x(n) + b(2)*x(n-1) + ... + b(nb+1)*x(nnb) - a(2)*y(n-1) - ... - a(na+1)*y(nna) >> filter(ones(1,3), 3, rpm_raw) ans = 359 351 335.67 719 724.33 667 1088.3 1081.7 1001 1084 1091.7 1004.7 1081 1073 1006.7
M S Ramaiah School of Advanced Studies

This example uses an FIR filter to compute a moving average using a window size of 3

11 2

Filtered Data Plot

M S Ramaiah School of Advanced Studies

11 3

Load .dat file and carryout analysis


% power spectrum in dB
% MATLAB PROGRAM ecg_hfn.m clear all % clears all active variables close all ecg = load('ecg_hfn.dat'); fs = 1000; %sampling rate = 1000 Hz zero_padding = 0; % Number of samples to be added as zero padding slen = length(ecg); %signal length t=[1:slen]/fs; ts=1/fs; figure(1) subplot(2,1,1),plot(t, ecg) axis tight; xlabel('Time in seconds'); ylabel('Amplitude in mV'); Title('Raw ECG'); % frequency domain fft_samples = 2^nextpow2(slen + zero_padding); raw_fft = fft(ecg,fft_samples); f_axis = 0:1:(fft_samples-1)/2; % fft_samples -1 because we start at 0 avg_power = sum(abs(raw_fft(1:fft_samples/2)).^2./slen)/slen; subplot(2,1,2) plot( f_axis*fs/fft_samples, ... abs(raw_fft(1:fft_samples/2))*2/slen,f_axis*fs/fft_samples,avg_power); title('Raw ECG Frequency Domain'); ylabel('Magnitude [Normalized]'); xlabel('Frequency [Hz]');

figure(3); psd(ecg,slen,1000) title('Power spectral density'); % high pass filter

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');

M S Ramaiah School of Advanced Studies

11 4

Load .dat file and carryout analysis


% frequency domain raw_fft1= fft(h1,fft_samples); f_axis1= 0:1:(fft_samples-1)/2; % fft_samples -1 because we start at 0 avg_power1 = sum(abs(raw_fft1(1:fft_samples/2)).^2./slen)/slen; figure(7); plot( f_axis1*fs/fft_samples, ... abs(raw_fft1(1:fft_samples/2))*2/slen,f_axis1*fs/fft_samples,avg_power1); title('High pass filtered ECG signal frequency domain'); ylabel('Magnitude [Normalized]'); xlabel('Frequency [Hz]');

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 f = 0:fs/2; F0 = 60; delF = 2;

% Center frequency of notch filter in Hz % bandwidth in Hz

Theta0 = (2*pi*F0)/fs; r = 1 - (delF*pi)/fs;

% 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

M S Ramaiah School of Advanced Studies

11 5

Load .dat file and carryout analysis


% IIR Low pass filter fc3= 40; n3=2; wn3=(2*fc3/fs); [b3,a3] = butter(n3,wn3); h3=filter(b3,a3,h2); figure(11); plot(h3); xlabel('Time in seconds'); title('Low pass filtered ECG at 40 Hz'); ylabel('LPF ECG'); figure(12) freqz(b3,a3); title('Low Pass Filter characteristics');

% 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');

M S Ramaiah School of Advanced Studies

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.

M S Ramaiah School of Advanced Studies

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);

M S Ramaiah School of Advanced Studies

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.

M S Ramaiah School of Advanced Studies

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

M S Ramaiah School of Advanced Studies

Matrix Factorizations: chol


chol: factors a symmetric, positive definite matrix A as RTR, where R is upper triangular.
>> A = [2 -1; 1 1; 6 -1]; >> B = A'*A B = 41 -7 -7 3 >> R = chol(B) R = 6.4031 1.0932 0 1.3435 >> R'*R ans = 41 -7 -7 3

Useful in solving least squares problems.

M S Ramaiah School of Advanced Studies

Eigenvalues and Eigenvectors: eig


eig: computes the eigenvalues, i and eigenvectors, xi of a square matrix A.. i and xi satisfy Axi = i xi
>> A = [1 -1 0; 0 1 1; 0 0 2]; >> [V, D] = eig(A) V = 1 1 -0.10483 0 0 -0.31449 0 0 0.94346 D = 1 0 0 0 1 0 0 0 -2 >> [A*V(:,3) D(3,3)*V(:,3)] ans = 0.20966 0.20966 0.62897 0.62897 -1.8869 -1.8869

[V,D] = eig(A) returns the eigenvectors of A in the columns of V, and the eigenvalues in the diagonal elements of D.

M S Ramaiah School of Advanced Studies

Singular Value Decomposition: svd


svd: factors an n x m matrix >> A = [2 -1; 1 1; 6 -1]; A as A = USVT, where U >> [U,S,V] = svd(A) and V are orthogonal U = matrices, and S is a -0.32993 0.47852 0.81373 diagonal matrix with -0.12445 -0.87653 singular values of A.

Useful in solving least squares problems.

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

M S Ramaiah School of Advanced Studies

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

MATLAB uses the SVD of A to compute pinv.


Useful in solving least squares problems.

M S Ramaiah School of Advanced Studies

Numerical Integration
trapz: Trapezoidal integration

quad: Adaptive, recursive Simpsons Rule for quadrature quadl: Adaptive, recursive Newton-Coates
8-panel rule

dblquad: Double integration using quad or quadl


12 5

M S Ramaiah School of Advanced Studies

Integration Example: humps Function


>> x = linspace(-1,2,150); >> y = humps(x); >> plot(x,y) >> format long >> trapz(x,y) % 5-digit accuracy ans = 26.344859225225534 >> quad('humps', -1, 2) % 6-digit accuracy ans = 26.344960501201232 >> quadl('humps', -1, 2) % 8-digit accuracy ans = 26.344960471378968

M S Ramaiah School of Advanced Studies

12 6

Root Finding and Minimization


roots: finds roots of polynomials fzero: finds roots of a nonlinear function of one variable fminbnd, fminsearch: finds maxima and minima of functions of one and several variables

M S Ramaiah School of Advanced Studies

12 7

Example of Polynomial Roots

p(x)=x3+4x2-7x-10

M S Ramaiah School of Advanced Studies

12 8

Example of Roots for Nonlinear Functions

M S Ramaiah School of Advanced Studies

12 9

Example of Function Minimization


>> p = [1 0 -2 -5]; >> x = linspace(0,2,100); >> y = polyval(p,x); >> plot(x,y) >> fminbnd('x.^3-2*x-5',0,2) ans = 0.8165
>> polyval(p,ans) ans = -6.0887

M S Ramaiah School of Advanced Studies

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

M S Ramaiah School of Advanced Studies

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?

M S Ramaiah School of Advanced Studies

13 2

Tool boxes
Signal and Image processing Audio processing wavread aviread

M S Ramaiah School of Advanced Studies

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');

M S Ramaiah School of Advanced Studies

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)

M S Ramaiah School of Advanced Studies

13 5

Thank You

M S Ramaiah School of Advanced Studies

13 6

You might also like