+ All Categories

Matlab

Date post: 17-May-2015
Category:
Upload: hira-sisodiya
View: 2,273 times
Download: 0 times
Share this document with a friend
Description:
matlab study
Popular Tags:
79
1 C Language is Simplest. C Language is Simplest.
Transcript
Page 1: Matlab

11

C Language is Simplest. C Language is Simplest.

Page 2: Matlab

22

What may be the size of the program for What may be the size of the program for writing a C code that generates sin wave?

Page 3: Matlab

33

But we can do the same by only three But we can do the same by only three lines.

Page 4: Matlab

44x=0.1:0.1:10;

b=sin(x);

Plot(x,b)

------ no

computational

complexity

Page 5: Matlab

55

That is the beauty we have as an engineer. engineer.

Name is

MATLAB

Page 6: Matlab

66

Recent Trends in Computationaltechniques for Engineering

Use of MATLAB in

Prof. Ashish M. KothariDepartment of Electronics & Communication EngineeringDepartment of Electronics & Communication Engineering

AtmiyaAtmiya Institute of Technology & Science, RajkotInstitute of Technology & Science, Rajkot

Engineering

Page 7: Matlab

7

Topics..

� What is MATLAB ??

� Basic Matrix Operations

� Script Files and M-files

� Some more Operations and Functions

� Plotting functions ..� Plotting functions ..

Page 8: Matlab

8

Topics..

� What is MATLAB ??

� Basic Matrix Operations

� Script Files and M-files

� Some more Operations and Functions

� Plotting functions � Plotting functions

Page 9: Matlab

9

MATLAB

� “MATrix LABoratory”

� Powerful, extensible, highly integrated computation, programming, visualization, and simulation packagesimulation package

� Widely used in engineering, mathematics, and science

Page 10: Matlab

10

MATLAB

Everything in MATLAB is a matrix !

Page 11: Matlab

MATLAB- Starting & Quiting11

Starting MATLAB

On a Microsoft Windows platform, to start MATLAB, double-click theMATLAB shortcut icon on your Windows desktop.MATLAB shortcut icon on your Windows desktop.

On Linux, to start MATLAB, type matlab at the operating system prompt.

After starting MATLAB, the MATLAB desktop opens – see “MATLABDesktop”.

You can change the directory in which MATLAB starts, define startupoptions including running a script upon startup, and reduce startup time insome situations.

Page 12: Matlab

MATLAB- Starting & Quiting12

Quiting MATLAB

To end your MATLAB session, select Exit MATLAB from theFile menu in the desktop, or type quit in the CommandFile menu in the desktop, or type quit in the CommandWindow.

Page 13: Matlab

13

The MATLAB Desktop

Page 14: Matlab
Page 15: Matlab

15

MATLAB Variable

� Variable names ARE case sensitive

� Variable names can contain up to 63 characters (as of MATLAB 6.5 and newer)

� Variable names must start with a letter followed by letters, digits, and underscores.

Page 16: Matlab

16

MATLAB Variable

no declarations needed

mixed data types

>> 16 + 24

ans =

40

>> product = 16 * 23.24 mixed data types

semi-colon suppresses output of the calculation’s result

>> product = 16 * 23.24

product =

371.84

>> product = 16 *555.24;

>> product

product =

8883.8

Page 17: Matlab

17

MATLAB Variable

complex numbers (i or j ) require no special handling

clear removes all variables;

clear x y removes only x and y

>> clear

>> product = 2 * 3^3;

>> comp_sum = (2 + 3i) + (2 - 3i);

>> show_i = i^2;

>> save three_things

>> clear

>> load three_things

save /load are used to

retain/restore workspace variables

>> load three_things

>> who

Your variables are:

comp_sum product show_i

>> product

product =

54

>> show_i

show_i =

-1

use home to clear screen and put cursor at the top of the screen

Page 18: Matlab

18

MATLAB Special Variables

ans Default variable name for results

pi Value of ππππeps Smallest incremental number

inf Infinity

NaN Not a number e.g. 0/0NaN Not a number e.g. 0/0

i and j i = j = square root of -1

realmin The smallest usable positive real number

realmax The largest usable positive real number

Page 19: Matlab

19

Topics..

� What is MATLAB ??

� Basic Matrix Operations

� Script Files and M-files

� Some more Operations and Functions

� Plotting functions ..� Plotting functions ..

Page 20: Matlab

20

Math & Assignment Operators

Power ^ or .^ e.g a^b or a.^b

Multiplication * or .* e.g a*b or a.*b

Division / or ./ e.g a/b or a./b

or \ or .\ e.g b\a or b.\a

NOTE: 56/8 = 8 \ 56NOTE: 56/8 = 8 \ 56

- (unary) + (unary)Addition + a + bSubtraction - a - bAssignment = a = b (assign b to a)

Page 21: Matlab

21

Other MATLAB symbols

>> prompt

. . . continue statement on next line

, separate statements and data, separate statements and data

% start comment which ends at end of line

; (1) suppress output

(2) used as a row separator in a matrix

: specify range

Page 22: Matlab

22

MATLAB Relational Operators

� MATLAB supports six relational operators.

Less Than <

Less Than or Equal <=Less Than or Equal <=

Greater Than >

Greater Than or Equal >=

Equal To ==

Not Equal To ~=

Page 23: Matlab

23

MATLAB Logical Operators

� MATLAB supports three logical operators.

not ~ % highest precedencenot ~ % highest precedence

and & % equal precedence with or

or | % equal precedence with and

Page 24: Matlab

24

MATLAB Matrices

� MATLAB treats all variables as matrices. For our purposes a matrix can be thought of as an array, in fact, that is how it is stored.

� Vectors are special forms of matrices and contain only one � Vectors are special forms of matrices and contain only one row OR one column.

� Scalars are matrices with only one row AND one column

Page 25: Matlab

25

MATLAB Matrices

� A matrix with only one row AND one column is a scalar. A scalar can be created in MATLAB as follows:

» a_value=23

a_value =

23

Page 26: Matlab

26

MATLAB Matrices

� A matrix with only one row is called a row vector. A row vector can be created in MATLAB as follows (note the commas):

» rowvec = [12 , 14 , 63]» rowvec = [12 , 14 , 63]

rowvec =

12 14 63

Page 27: Matlab

27

MATLAB Matrices

� A matrix with only one column is called a column vector. A column vector can be created in MATLAB as follows (note the semicolons):

» colvec = [13 ; 45 ; -2]» colvec = [13 ; 45 ; -2]

colvec =

13

45

-2

Page 28: Matlab

28

MATLAB Matrices

� A matrix can be created in MATLAB as follows (note the commas AND semicolons):

» matrix = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9]

matrix =

1 2 3

4 5 6

7 8 9

Page 29: Matlab

29

Extracting a Sub-Matrix

� A portion of a matrix can be extracted and stored in a smaller matrix by specifying the names of both matrices and the rows and columns to extract. The syntax is:

sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ;sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ;

where r1 and r2 specify the beginning and ending rows and c1 and c2 specify the beginning and ending columns to be extracted to make the new matrix.

Page 30: Matlab

30

MATLAB Matrices

� A column vector can be extracted from a matrix. As an example we create a matrix below:

» matrix=[1,2,3;4,5,6;7,8,9]

� Here we extract column 2 of the matrix and make a column vector:

» col_two=matrix( : , 2)» matrix=[1,2,3;4,5,6;7,8,9]

matrix =

1 2 3

4 5 6

7 8 9

» col_two=matrix( : , 2)

col_two =

2

5

8

Page 31: Matlab

31

MATLAB Matrices

� A row vector can be extracted from a matrix. As an example we create a matrix below:

» matrix=[1,2,3;4,5,6;7,8,9]

� Here we extract row 2 of the matrix and make a row vector. Note that the 2:2 specifies the second row and the 1:3 specifies which columns of the row.

» matrix=[1,2,3;4,5,6;7,8,9]

matrix =

1 2 3

4 5 6

7 8 9

of the row.

» rowvec=matrix(2 : 2 , 1 : 3)

rowvec =

4 5 6

Page 32: Matlab

32

Topics..

� What is MATLAB ??

� Basic Matrix Operations

� Script Files /M-files and Function Files

� Some more Operations and Functions

� Plotting functions ..� Plotting functions ..

Page 33: Matlab

33

Use of M-File

� There are two kinds of M-files:

�Scripts, which do not accept input arguments or return output arguments. They operate on data in the workspace.

�Functions, which can accept input

arguments and return output arguments. Internal variables are local to the function.

Click to create a new M-File

Page 34: Matlab

34

M-File as script file

Save file as filename.m

Type what you want to do, eg. Create matrices

If you include “;” at the end of each statement,result will not be shown immediately

Run the file by typing the filename in the command window

Page 35: Matlab

35

MATLAB Function File

function [a b c] = myfun(x, y)b = x * y; a = 100; c = x.^2;

>> myfun(2,3) % called with zero outputsans =

100>> u = myfun (2,3) % called with one output

Write these two lines to a file myfun.mand save it on MATLAB’s path

>> u = myfun (2,3) % called with one outputu =

100>> [u v w] = myfun(2,3) % called with all outputsu =

100v =

6w =

4

Any return value which is not stored in an output variable is simply discarded

Page 36: Matlab

36

Topics..

� What is MATLAB ??

� Basic Matrix Operations

� Script Files and M-files

� Some more Operations and Functions

� Plotting functions ..� Plotting functions ..

Page 37: Matlab

37

Some Useful MATLAB commands

� who List known variables

� whos List known variables plus their size

� help >> help sqrt Help on using sqrt

� lookfor >> lookfor sqrt Search for� lookfor >> lookfor sqrt Search for

keyword sqrt in m-files

� what >> what a: List MATLAB files in a:

� clear Clear all variables from work space

� clear x y Clear variables x and y from work space

� clc Clear the command window

Page 38: Matlab

38Some Useful MATLAB commands

� what List all m-files in current directory

� dir List all files in current directory

� ls Same as dir

� type test Display test.m in command window

� delete test Delete test.m� delete test Delete test.m

� cd a: Change directory to a:

� chdir a: Same as cd

� pwd Show current directory

� which test Display directory path to ‘closest’ test.m

Page 39: Matlab

39

MATLAB Logical Functions

� MATLAB also supports some logical functions.

xor (exclusive or) Ex: xor (a, b)

Where a and b are logical expressions. The xoroperator evaluates to true if and only if one expression is true and the other is false. True is returned as 1, false as 0.returned as 1, false as 0.

any (x) returns 1 if any element of x is nonzero

all (x) returns 1 if all elements of x are nonzero

isnan (x) returns 1 at each NaN in x

isinf (x) returns 1 at each infinity in x

finite (x) returns 1 at each finite value in x

Page 40: Matlab

40Matlab Selection Structures

� An if - elseif - else structure in MATLAB.

Note that elseif is one word.

if expression1 % is true

% execute these commands

elseif expression2 % is true

% execute these commands

else % the default

% execute these commands

end

Page 41: Matlab

41

MATLAB Repetition Structures

A for loop in MATLAB for x = arrayfor ind = 1:100

b(ind)=sin(ind/10)end

while loop in MATLAB while expressionwhile x <= 10

% execute these commandsend

Page 42: Matlab

42

x=0.1:0.1:10;

b=sin(x);

Plot(b,x)

------ no

computational

complexity

Page 43: Matlab

43

Scalar - Matrix Addition

» a=3;

» b=[1, 2, 3;4, 5, 6]

b =

1 2 3

4 5 64 5 6

» c= b+a % Add a to each element of b

c =

4 5 6

7 8 9

Page 44: Matlab

44

Scalar - Matrix Subtraction

» a=3;

» b=[1, 2, 3;4, 5, 6]

b =

1 2 31 2 3

4 5 6

» c = b - a %Subtract a from each element of b

c =

-2 -1 0

1 2 3

Page 45: Matlab

45

Scalar - Matrix Multiplication

» a=3;

» b=[1, 2, 3; 4, 5, 6]

b =

1 2 31 2 3

4 5 6

» c = a * b % Multiply each element of b by a

c =

3 6 9

12 15 18

Page 46: Matlab

46

Scalar - Matrix Division

» a=3;

» b=[1, 2, 3; 4, 5, 6]

b =

1 2 31 2 3

4 5 6

» c = b / a % Divide each element of b by a

c =

0.3333 0.6667 1.0000

1.3333 1.6667 2.0000

Page 47: Matlab

47

The use of “.” – “Element” Operation

Given A:

Divide each element of Multiply each Square each Divide each element of A by 2

Multiply each element of A by 3

Square each element of A

Page 48: Matlab

4848

MATLAB Toolboxes

� MATLAB has a number of add-on software modules, called toolbox , that perform more specialized computations.

� Signal Processing� Image Processing � Communications� Communications� System Identification� Wavelet Filter Design � Control System � Fuzzy Logic� Robust Control� µ-Analysis and Synthesis� LMI Control � Model Predictive Control� …

Page 49: Matlab

4949

MATLAB Demo

� Demonstrations are invaluable since they give an indication of the MATLAB capabilities.

� A comprehensive set are available by typing the command � A comprehensive set are available by typing the command >>demodemo in MATLAB prompt.

Page 50: Matlab

50

An Interesting, MATLAB command

why

In case you ever needed a reason

Page 51: Matlab

51

Topics..

� What is MATLAB ??

� Basic Matrix Operations

� Script Files and M-files

� Some more Operations and Functions

� Plotting functions ..� Plotting functions ..

Page 52: Matlab

Plot

PLOT Linear plot.

� PLOT(X,Y) plots vector Y versus vector X

� PLOT(Y) plots the columns of Y versus their index

x = [-3 -2 -1 0 1 2 3];y1 = (x.^2) -1;plot(x, y1, 'bo-.' );

Example

52

52

� PLOT(X,Y,S) with plot symbols and colors

� See also SEMILOGX, SEMILOGY, TITLE, XLABEL, YLABEL, AXIS, AXES, HOLD, COLORDEF, LEGEND, SUBPLOT...

Page 53: Matlab

Plot Properties

XLABEL X-axis label.

� XLABEL('text') adds text beside the X-axis on the current axis.

...xlabel( 'x values' );ylabel( 'y values' );

Example

53

53

YLABEL Y-axis label.

� YLABEL('text') adds text beside the Y-axis on the current axis.

Page 54: Matlab

Hold

HOLD Hold current graph.

� HOLD ON holds the current plot and all axis properties so that subsequent graphing commands add to the existing

...hold on;y2 = x + 2;plot(x, y2, 'g+:' );

Example

54

54

commands add to the existing graph.

� HOLD OFF returns to the default mode

� HOLD, by itself, toggles the hold state.

Page 55: Matlab

Subplot

SUBPLOT Create axes in tiled positions.

� SUBPLOT(m,n,p), or SUBPLOT(mnp), breaks the Figure window into an m-by-n matrix of small axes

55

55

x = [-3 -2 -1 0 1 2 3];y1 = (x.^2) -1;% Plot y1 on the topsubplot(2,1,1);plot(x, y1, 'bo-.' );xlabel( 'x values' );ylabel( 'y values' );% Plot y2 on the bottomsubplot(2,1,2);y2 = x + 2;plot(x, y2, 'g+:' );

Example

Page 56: Matlab

Figure

FIGURE Create figure window.

� FIGURE, by itself, creates a new figure window, and returns its handle.

56

56

x = [-3 -2 -1 0 1 2 3];y1 = (x.^2) -1;% Plot y1 in the 1 st Figureplot(x, y1, 'bo-.' );xlabel( 'x values' );ylabel( 'y values' );% Plot y2 in the 2 nd Figurefigurey2 = x + 2;plot(x, y2, 'g+:' );

Example

Page 57: Matlab

Surface Plot

x = 0:0.1:2;y = 0:0.1:2;[xx, yy] = meshgrid(x,y);zz=sin(xx.^2+yy.^2);surf(xx,yy,zz)xlabel('X axes')ylabel('Y axes')

57

57

Page 58: Matlab

contourf-colorbar-plot3-waterfall-contour3-mesh-surf

3 D Surface Plot58

58

Page 59: Matlab

MATLAB Applications

>> t=-2*pi:0.1:2*pi;

y=1.5*sin(t);

plot(t,y);

xlabel(' ------ > time')

59

DSP

59

xlabel(' ------ > time')

ylabel('------> sin(t)')

Page 60: Matlab

MATLAB Applications

>> t=-2*pi:0.1:2*pi;

y=1.5*cos(t);

stem(t,y);

xlabel(' ------ > time')

60

DSP

60

xlabel(' ------ > time')

ylabel('------> sin(t)')

Page 61: Matlab

MATLAB Applications

� n=input('enter value of n')

� t=0:1:n-1;

� y1=ones(1,n); %unit step

� y2=[zeros(1,4) ones(1,n-4)]; %delayed unit step

61

DSP

61

� y2=[zeros(1,4) ones(1,n-4)]; %delayed unit step

� subplot(2,1,1);

� stem(t,y1,'filled');ylabel('amplitude');

� xlabel('n----->');ylabel('amplitude');

� subplot(2,1,2);

� stem(t,y2,'filled');

� xlabel('n----->');ylabel('amplitude');

Page 62: Matlab

MATLAB Applications 62

DSP

62

Page 63: Matlab

MATLAB Applications

Control Systems

1

1 2 1...( )

n n

np s p s pH s

−++ + +=

Transfer Function

63

63

1 2 11

1 1 1

1 2 1

1 1 1

...( )

...

, ... numerator coefficients

, ... denominator coefficients

n

m m

m

n

m

p s p s pH s

q s q s q

where

p p p

q q q

+−

+

+

+

+ + +=+ + +

Page 64: Matlab

MATLAB Applications

Control Systems

� Consider a linear time invariant (LTI) single-input/single-output system

Transfer Function

64

64

� Applying Laplace Transform to both sides with zero initial conditions

'' 6 ' 5 4 ' 3y y y u u+ + = +

2

( ) 4 3( )

( ) 6 5

Y s sG s

U s s s

+= =+ +

Page 65: Matlab

MATLAB Applications

Control SystemsTransfer Function

>> num = [4 3];>> den = [1 6 5];

>> [num,den] = tfdata(sys,'v')

num =

65

65

>> sys = tf(num,den)Transfer function:

4 s + 3-----------------s^2 + 6 s + 5

num = 0 4 3

den =1 6 5

Page 66: Matlab

MATLAB Applications

Control Systems

Zero-pole-gain model (ZPK)

1 2( )( ) ... ( )( )

( )( ) ... ( )ns p s p s p

H s Ks q s q s q

− − + + −=− − + + −

66

66

1 2

1 2 1

1 1 1

( )( ) ... ( )

, ... the zeros of H(s)

, ... the poles of H(s)

m

n

m

s q s q s q

where

p p p

q q q+

+

− − + + −

Page 67: Matlab

MATLAB Applications

Control Systems

� Consider a Linear time invariant (LTI) single-input/single-output system

'' 6 ' 5 4 ' 3y y y u u+ + = +

Zero-pole-gain model (ZPK)

67

67

� Applying Laplace Transform to both sides with zero initial conditions

'' 6 ' 5 4 ' 3y y y u u+ + = +

2

( ) 4 3 4( 0.75)( )

( ) ( 1)( 5)6 5

Y s s sG s

U s s ss s

+ += = =+ ++ +

Page 68: Matlab

MATLAB Applications

Control Systems

>> G=tf([4 3],[1 6 5])

Transfer function:4 s + 3

-------------

>> [z,p,k]=zpkdata(G)

z = [-0.7500]

68

68

-------------s^2 + 6 s + 5 p =

[-5;-1]

k =4

Page 69: Matlab

MATLAB Applications

Control Systems

>> bode(G)

69

69

Page 70: Matlab

MATLAB Applications

Control Systems

>> rlocus(G)

70

70

Page 71: Matlab

MATLAB Applications

Control Systems

>> nyquist(G)

71

71

Page 72: Matlab

MATLAB Applications

Control Systems

>> step(G)

72

72

Page 73: Matlab

MATLAB Applications

Control Systems

>> impulse(G)

73

73

Page 74: Matlab

MATLAB Applications

Communication

>> t=0:pi/100:2*pi;>> x=sin(t);>> subplot(211);plot(t,x);>> Fc=1000;>> Fs=2000;

74

74

>> y=ammod(x,Fc,Fs);>> subplot(212);plot(t,y);

Page 75: Matlab

MATLAB Applications

Communication75

75

Page 76: Matlab

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/

76

76

� 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

Page 77: Matlab

Reference Books

Mastering MATLAB 7, D. Hanselman and B. Littlefield,Prentice Hall, 2004

77

77

Getting Started with MATLAB 7: A Quick Introductionfor Scientists and Engineers, R. Pratap, Oxford UniversityPress, 2005.

Page 78: Matlab

Some More Web Resources

78

MATLAB Educational sites:

http://www.eece.maine.edu/mm/matweb.html

Yahoo! MATLAB Web site:

78

Yahoo! MATLAB Web site:

dir.yahoo.com/Science/mathematics/software/matlab/

Newsgroup:

comp.soft-sys.matlab

Page 79: Matlab

79

Thanks

Questions ??


Recommended