121782824 introduction to matlab

136
© M S Ramaiah School of Advanced Studies Introduction to MATLAB Preetham Shankpal Asst. Professor, M S Ramaiah School of Advanced Studies Email: [email protected] 1

Upload: sattar-al-jabair

Post on 08-Nov-2014

71 views

Category:

Documents


1 download

DESCRIPTION

Matlab

TRANSCRIPT

Page 1: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Introduction to MATLAB

Preetham Shankpal

Asst. Professor,

M S Ramaiah School of Advanced Studies

Email: [email protected]

1

Page 2: 121782824 Introduction to Matlab

© 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

2

Page 3: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

MATLAB Toolboxes

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

HELP WINDOW - DEMOS

3

Page 4: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Toolboxes, Software, & Links

4

Page 5: 121782824 Introduction to Matlab

© 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

5

Page 6: 121782824 Introduction to Matlab

© 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

6

Page 7: 121782824 Introduction to Matlab

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

7

Page 8: 121782824 Introduction to Matlab

© 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

Page 9: 121782824 Introduction to Matlab

© 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

array‟s name in the Workspace)

• Editor/Debugger: text editor, debugger; editor works with file types

in addition to .m (MATLAB “m-files”)

9

Page 10: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

MATLAB Editor Window

10

Page 11: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

MATLAB Help Window (Very Powerful)

11

Page 12: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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.

12

Page 13: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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 Size Bytes Class Attributes

ans 1x1 8 double

fid 1x1 8 double

i 1x1 8 double

13

Page 14: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Variables (Arrays) and Operators

14

Page 15: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

Page 16: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

Page 17: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Matlab as Calculator

no declarations needed

mixed data

types

semi-colon suppresses output

of the calculation’s result

>> 16 + 24

ans =

40

>> product = 16 * 23.24

product =

371.84

>> product = 16 *555.24;

>> product

product =

8883.8

17

Page 18: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

Page 19: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

19

Page 20: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

20

Page 21: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

Page 22: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

complex numbers (i or j) require

no special handling

save/load are used to

retain/restore workspace variables

Solve in MATLAB

22

Page 23: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

Page 24: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Suppressing Output

• One often does not want to see the result of intermediate

calculations terminate the assignment statement or expression with

semicolon

• the value of x is hidden. Note also we can place several statements

on one line, separated by commas or semicolons

24

>> x=-13; y = 5*x, z = x^2+y

y =

-65.00

z =

104.00

Page 25: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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.

• The inverse trig functions are called asin, acos, atan (as opposed to

the usual arcsin or sin-1 etc.). The result is in radians.

25

>> x = 5*cos(pi/6), y = 5*sin(pi/6)

x =

4.33

y =

2.50

acos(x/5), asin(y/5)

ans =

0.52

ans =

0.52

>> pi/6

ans =

0.52

Page 26: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Other Elementary Functions

• These include sqrt, exp, log, log10

26

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

Page 27: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

• Spaces can be vitally important:

27

>> v = [ 1 3, sqrt(5)]

v =

1.00 3.00 2.24

>> length(v)

ans =

3.00 >> v2 = [3+ 4 5]

v2 =

7.00 5.00

>> v2 = [3 +4 5]

v2 =

3.00 4.00 5.00

Page 28: 121782824 Introduction to Matlab

© 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

28

>> v, v3, v+v3

v =

1.00 3.00 2.24

v3 =

3.00 4.00 5.00

ans =

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

The error is due to v and

v2 having different lengths

Page 29: 121782824 Introduction to Matlab

© 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

• We can build row vectors from existing ones:

29

>> v, v4=3*v

v =

1.00 3.00 2.24

v4 =

3.00 9.00 6.71

>> w = [1 2 3], z = [8 9]

cd = [2*z,-w], sort(cd)

w =

1.00 2.00 3.00

z =

8.00 9.00

cd =

16.00 18.00 -1.00 -2.00 -3.00

ans =

-3.00 -2.00 -1.00 16.00 18.00

Page 30: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Row vectors

• We can also change or look at the value of particular entries

30

w(2) = -2, w(3)

w =

1.00 -2.00 3.00

ans =

3.00

Page 31: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

The Colon Notation

• This is a shortcut for producing row vectors:

• 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 [].

31

>> a= 1:4

a =

1.00 2.00 3.00 4.00

>> b=3:7

b =

3.00 4.00 5.00 6.00 7.00

>> c=-1:1

c =

-1.00 0 1.00

>> d=1:-1

d =

Empty matrix: 1-by-0

Upper limit lower limit

>> 1:3:7

ans =

1.00 4.00 7.00

Page 32: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Extracting Bits of a Vector

• To get the 3rd to 6th entries:

• To get alternate entries

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

32

>> r5 = [1:2:6, -1:-2:-7]

r5 =

1.00 3.00 5.00 -1.00 -3.00 -5.00 -7.00

>> r5(3:6)

ans =

5.00 -1.00 -3.00 -5.00

>> r5(1:2:7)

ans =

1.00 5.00 -3.00 -7.00

>> r5(6:-2:1)

ans =

-5.00 -1.00 3.00

Page 33: 121782824 Introduction to Matlab

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

so column vectors may be added or subtracted provided that they

have the same length

33

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

Page 34: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Transposing a Matrix

• We can convert a row vector into a column vector (and vice versa)

by a process called transposing denoted by „.

• If x is a complex vector, then x' gives the complex conjugate

transpose of x:

34

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

a=[1-1i 1+1i];

b=a';

1.00 - 1.00i 1.00+1.00i 1.00 + 1.00i

1.00 - 1.00i

Page 35: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Plotting Elementary Functions

• Plot(t, sin(2*pi*100*t))

• xlabel

• ylabel

• title

• grid

• figure

35

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)

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1-3

-2

-1

0

1

2

3

0 0.01 0.02 0.03 0.04 0.05 0.06 0.07-3

-2

-1

0

1

2

3

Page 36: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Multiple Plots

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

• xlabel

• ylabel

• title

• hold on

• subplot

• Data cursor (marker)

36

0 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1-3

-2

-1

0

1

2

3

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

Page 37: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

37

Page 38: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

2D MATRIX Declaration

• M=[3 4 5; 6 7 8; 1 -1 0]

• M=magic(4)

38

>> a=[1;2;3];

>> b=[3;4;5];

>> c=[2;3;4];

>> s=[a b c]

s =

1.00 3.00 2.00

2.00 4.00 3.00

3.00 5.00 4.00

Page 39: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Matrices: Magic Squares

This matrix is called a

“magic square”

Interestingly,

Durer also dated

this engraving

by placing 15

and 14 side-by-

side in the

magic square.

39

Page 40: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

40

Page 41: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Matrix Manipulations

• Scalar Product (*)

• u= [ 1 2 3]; v= [2;3;4] ;

• Scalar_product= 1x2+2x3+3x4=20

• (row vector x column vector)

• (row vector x column vector)

• an error results because w is not a column vector

41

1

N

i i

i

uv u v

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

Page 42: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

42

>> u= [ 1 2 3]; v= [2 3 4];

>> u*v

??? Error using ==> mtimes

Inner matrix dimensions must agree.

>> u.*v

ans =

2.00 6.00 12.00

Tabulate the function y = x sin(pi* x) for

x = 0; 0:25; : : : ; 1.

plot(x,y)

Page 43: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

43

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

Page 44: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

44

>> a=[ 1 2 3];

>> a=a.^2

a =

1.00 4.00 9.00

a =

1.00 4.00 9.00

>> a=a.^4

a =

1.00 256.00 6561.00

Draw plots for the following

Page 45: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Multidimensional Arrays

>> r = randn(2,3,2) % create a 3 dimensional array filled

%with normally distributed random numbers

randn(2,3,2): 3 dimensions, filled

with normally distributed random

numbers

“%” sign precedes comments,

MATLAB ignores the rest of the line r=rand(2,3,2) r(:,:,1) = 0.2769 0.0971 0.6948 0.0462 0.8235 0.3171 r(:,:,2) = 0.9502 0.4387 0.7655 0.0344 0.3816 0.7952

45

Page 46: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

2D Matrix Manipulations • size(A) , max, min transpose(A), size(A)

• diag(A) fliplr(A)

• A=zeros(m,n) eye(A)

46

>> a= [ 2 3 4; 2 4 5; 5 6 7]

a =

2.00 3.00 4.00

2.00 4.00 5.00

5.00 6.00 7.00

>> size(a)

ans =

3.00 3.00

>> diag(a)

ans =

2.00

4.00

7.00

>> a= [ 2 3 4; 2 4 5]

a =

2.00 3.00 4.00

2.00 4.00 5.00

>> size(a)

ans =

2.00 3.00

>> a'

ans =

2.00 2.00

3.00 4.00

4.00 5.00

>> size(a')

ans =

3.00 2.00

zeros(2,4)

ans =

0 0 0 0

0 0 0 0

>> eye(3)

ans =

1.00 0 0

0 1.00 0

0 0 1.00

Page 47: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Matrix Manipulation • D=[1 2 3 4]; D=diag(1:4)

• 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];

47

>> diag(1:4)

ans =

1.00 0 0 0

0 2.00 0 0

0 0 3.00 0

0 0 0 4.00

Page 48: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

Page 49: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

49

>> 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 6.00 12.00 20.00

15.00 24.00 35.00 42.00

48.00 63.00 24.00 36.00

Page 50: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Sparse Matrix

• Create a sparse 5x4 matrix S having only 3 non{zero values: S1,2 =

10, S3,3 = 11 and S5,4 =12.

50

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

0 0 0 0

0 0 0 12.00

Page 51: 121782824 Introduction to Matlab

© 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

51

Page 52: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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.

52

Page 53: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Example

• Use the backslash operator to solve the complex system of equations

for which

53

Page 54: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Character Strings

• close all;

• clear all;

• clc

• hi = ' hello';

• class = 'MATLAB';

• greetings = [hi class]

• vgreetings = [hi;class]

semi-colon: join vertically

concatenation with blank or with “,”

54

Page 55: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

yo =

Hello

Class

>> ischar(yo)

ans =

1

>> strcmp(yo,yo)

ans =

1

String Functions

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

55

Page 56: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Set Functions

Arrays are ordered sets:

>> a = [1 2 3 4 5]

a =

1 2 3 4 5

>> b = [3 4 5 6 7]

b =

3 4 5 6 7

>> isequal(a,b)

ans =

0

>> ismember(a,b)

ans =

0 0 1 1 1

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

Page 57: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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 don‟t 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

Page 58: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

Page 59: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

Page 60: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Lab 3

60

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

Page 61: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Programming

61

Page 62: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

• 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

Outline

62

Page 63: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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-file Editor Window

63

Page 64: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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.

64

Page 65: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

function [a b c] = myfun(x, y)

b = x * y; a = 100; c = x.^2;

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

6

w =

4

Functions – First Example

Write these two lines to a file myfun.m and save it on MATLAB‟s path

Any return value which is not stored

in an output variable is simply

discarded

65

Page 66: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

Page 67: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Sum

• Produce a list of the values of the sums

67

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

Page 68: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

68

Page 69: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Discrete Fourier Transform Definition

21

0

21

0

[ ] [ ]

1[ ] [ ]

j knN

N

n

j knN

N

k

X k x n e

x n X k eN

69

Page 70: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

fft and fftshift

0 2

N=11

-

1 11

0

N=11

After fftshift

70

Page 71: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

71

Page 72: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

72

Page 73: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Frequency Spectrum

73

Page 74: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Area

74

function [A] = area(a,b,c)

s = (a+b+c)/2;

A = sqrt(s*(s-a)*(s-b)*(s-c));

Page 75: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

75

Page 76: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

76

Page 77: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

Page 78: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

Page 79: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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 0 25 36 49 64

0 0 36 49 64 81

0 0 49 64 81 100

0 0 64 81 100 121

79

Page 80: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

Page 81: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

MATLAB’s 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, ...

81

Page 82: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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.

• rmpath is used to remove paths from the search path

>> path

MATLABPATH

E:\MATLAB\R2006b\work

E:\MATLAB\R2006b\work\f_funcs

E:\MATLAB\R2006b\work\na_funcs

E:\MATLAB\R2006b\work\na_scripts

E:\MATLAB\R2006b\toolbox\matlab\genera

l

E:\MATLAB\R2006b\toolbox\matlab\ops

>> addpath('c:\');

>> matlabpath

MATLABPATH

c:\

E:\MATLAB\R2006b\work

E:\MATLAB\R2006b\work\f_funcs

E:\MATLAB\R2006b\work\na_funcs

E:\MATLAB\R2006b\work\na_scripts

E:\MATLAB\R2006b\toolbox\matlab\general

E:\MATLAB\R2006b\toolbox\matlab\ops

Page 83: 121782824 Introduction to Matlab

© 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 (we‟ll assume you placed your image in a

matrix named a) image(a); colormap(gray). (Don‟t worry if

this doesn‟t 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

Page 84: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Lab 2

• Write a MATLAB function that implements Newton‟s iterative algorithm for

approximating the square root of a number.

• The core of Newton‟s 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

Page 85: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Data I/O

85

Page 86: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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)

86

Page 87: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

87

Page 88: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

88

Page 89: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

89

Page 90: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

textread Example

• Data file,

tab delimited:

• MATLAB

m-file:

• Results:

‘param’,’value’ pairs

use doc textread for available param options

Page 91: 121782824 Introduction to Matlab

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

91

Page 92: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

92

Page 93: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

93

Page 94: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

File Open (fopen)/Close (fclose)

• fid = fopen(‘filename’, ‘permission’);

• status = fclose(fid);

File

identifier

number

Name of

file

Permission

requested: ‘r’, ’r+’

‘w’, ’w+’

‘a’, ’a+’

0, if successful

-1, otherwise File identifier number

or „all‟ for all files

94

Page 95: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Formatted I/O

• fscanf: [A, count] = fscanf(fid,format,size);

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

Data

array

Number

successfully

read

File

identifier

number

Amount of

data to read: n, [n, m], Inf

Format

specifier

Number

successfully

read

File

identifier

number

Format

specifier

Data

array(s) to

write

fscanf and fprintf are similar to C version but vectorized

95

Page 96: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Format String Specification

%-12.5e

initial %

character width and

precision

conversion

specifier alignment flag

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

Page 97: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

97

Page 98: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Binary File I/O

• [data, count] = fread(fid, num, precision);

• count = fwrite(fid, data, precision);

Data

array

Number

successfully

read

File

identifier

number

Amount to read n, [n, m],...

„int‟, „double‟, …

array to

write

Number

successfully

written

File

identifier

number

„int‟, „double‟, …

fread and fwrite are vectorized

98

Page 99: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Basic Data Analysis

99

Page 100: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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.

100

Page 101: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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.

101

Page 102: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Plotting the Data

Note that in this case

the plot command

generates one time-

series for each column

of the data matrix

>> plot(rpm_raw)

>> xlabel('sample number - during time slice');

>> ylabel('Unfiltered RPM Data');

>> title(‘3 sequences of samples from RPM sensor’)

102

Page 103: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Average of the Data:

Applying the mean function

to the data matrix yields the

mean of each column

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

1

2

>> mean(rpm_raw)

ans =

1081.4 1082.8

1002.7

>> mean(mean(rpm_raw))

ans =

1055.6

103

Page 104: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

The mean Function

But we can apply the mean function

along any dimension

So we can easily obtain the row

means

3

>> 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) is [1.5 2.5 3.5] and mean(X,2) is [1

4] >> mean(rpm_raw, 2)

ans =

1045.7

1064.7

1060.7

1055

1045

104

Page 105: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

max and its Index

We can compute the max of the entire matrix,

or of any dimension

1 2 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 non-

singleton dimension contain more

than one maximal element, the index

of the first one is returned.

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

105

Page 106: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

min

>> min(rpm_raw)

ans =

1053 1053 961

>> min(min(rpm_raw))

ans =

961

>> [y,i] = min(rpm_raw)

y =

1053 1053 961

i =

22 1 22

min along each column

min of entire matrix

106

Page 107: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

107

Page 108: 121782824 Introduction to Matlab

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

. . .

108

Page 109: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Histogram (cont.)

>> hist(rpm_raw) %histogram of the data

109

Page 110: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

110

Page 111: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Histogram (cont.)

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

111

Page 112: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

nb)

- a(2)*y(n-1) - ... - a(na+1)*y(n-

na)

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

This example uses an

FIR filter to compute a

moving average using a

window size of 3

112

Page 113: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Filtered Data Plot

113

Page 114: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Load .dat file and carryout analysis

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

% power spectrum in dB

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

114

Page 115: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

%notch filter

f = 0:fs/2;

F0 = 60; % Center frequency of notch filter in Hz

delF = 2; % 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

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

115

Page 116: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

116

Page 117: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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/2σ2)

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.

117

Page 118: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

118

Page 119: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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 figure‟s toolbar and determine the

frequencies of the 3 components.

119

Page 120: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

Page 121: 121782824 Introduction to Matlab

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

Useful in solving least

squares problems.

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

Page 122: 121782824 Introduction to Matlab

© 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

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

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

Page 123: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Singular Value Decomposition: svd

svd: factors an n x m matrix

A as A = USVT, where U

and V are orthogonal

matrices, and S is a

diagonal matrix with

singular values of A.

• Useful in solving least

squares problems.

>> A = [2 -1; 1 1; 6 -1];

>> [U,S,V] = svd(A)

U =

-0.32993 0.47852 -

0.81373

-0.12445 -0.87653 -

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

Page 124: 121782824 Introduction to Matlab

© 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

• MATLAB uses the SVD of A

to compute pinv.

• Useful in solving least squares

problems.

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

Page 125: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Numerical Integration

• trapz: Trapezoidal integration

• quad: Adaptive, recursive Simpson‟s Rule for

quadrature

• quadl: Adaptive, recursive Newton-Coates

8-panel rule

• dblquad: Double integration using quad or

quadl

125

Page 126: 121782824 Introduction to Matlab

© 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

126

Page 127: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

127

Page 128: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Example of Polynomial Roots

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

128

Page 129: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Example of Roots for Nonlinear Functions

129

Page 130: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

130

Page 131: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

131

Page 132: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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?

132

Page 133: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Tool boxes

• Signal and Image processing

• Audio processing

– wavread

– aviread

133

Page 134: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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

134

Page 135: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

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)

135

Page 136: 121782824 Introduction to Matlab

© M S Ramaiah School of Advanced Studies

Thank You

136