Top Banner
1 M M ATLAB ATLAB B B ASICS ASICS Sanjay R Joshi Sanjay R Joshi [email protected] [email protected] 20-Jan-2007 20-Jan-2007 MATLAB for ELECTRICAL ENGINEERING MATLAB for ELECTRICAL ENGINEERING EE DEPT EE DEPT IIT BOMBAY IIT BOMBAY
66

Matlab Basics MEE

Apr 18, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Matlab Basics MEE

1

MMATLABATLAB BBASICSASICS

Sanjay R JoshiSanjay R Joshi

[email protected]@yahoo.com20-Jan-200720-Jan-2007

MATLAB for ELECTRICAL ENGINEERINGMATLAB for ELECTRICAL ENGINEERING

EE DEPTEE DEPTIIT BOMBAYIIT BOMBAY

Page 2: Matlab Basics MEE

2

• MATLAB - developed by Math Works Inc.

•http://www.mathworks.com

•MATLAB - acronym for MATrix LABoratory

•Matrices and arrays - the heart of MATLAB

•Offers programming features - similar to other languages

•Offers GUI tools

Page 3: Matlab Basics MEE

3

Why MATLAB is Why MATLAB is popular ?popular ?

1.1. No need to declare dimensions of a No need to declare dimensions of a matrix as in FORTRAN or C.matrix as in FORTRAN or C.

2.2. Very powerful and easy-to-learn Very powerful and easy-to-learn graphics capabilities.graphics capabilities.

3.3. MATLAB can be integrated with MATLAB can be integrated with FORTRAN and C/C++ programs.FORTRAN and C/C++ programs.

4.4. MATLAB has many MATLAB has many toolboxestoolboxes ((collections of MATLAB functionscollections of MATLAB functions) ) applied to specific topics like control applied to specific topics like control system, symbolic manipulation, FFT etc.system, symbolic manipulation, FFT etc.

5.5. MATLAB has proved to be extremely MATLAB has proved to be extremely efficient and hence very fast for solving efficient and hence very fast for solving some problems.some problems.

Page 4: Matlab Basics MEE

4

•MATLAB is an interactive system for doing numerical computations

•Powerful operations can be performed using just one or two commands.

• There are more than 1000 functions in the basic MATLAB product alone.

•Modeling, simulation, Data analysis, exploration, and visualization and many more.

•Application development, including Graphical User Interface building.

Page 5: Matlab Basics MEE

5

Easy to use

Platform independence

Predefined functions

Device –independent plotting

Page 6: Matlab Basics MEE

6

MATLAB WINDOWS

COMMAND WINDOWCOMMAND WINDOW

To give MATLAB commands at the To give MATLAB commands at the promptprompt

EDIT/DEBUG WINDOWEDIT/DEBUG WINDOW

To create , edit and debug the To create , edit and debug the program. program.

Type edit at the command prompt.Type edit at the command prompt.

FIGURE WINDOWFIGURE WINDOW

To visualize graphs and plotsTo visualize graphs and plots

Page 7: Matlab Basics MEE

7

• Provides a variety of graphic output displays:

• linear

• log-log

• semilog

• polar

• bar chart, and

•contour plots

• 2-D and 3-D views

Page 8: Matlab Basics MEE

8

• Provides extensive numerical resources

• Over 200 reliable, accurate mathematical subprograms

• The subprograms provide solutions to broad range of mathematical problems including: matrix algebra ( Linear Algebra )

• complex arithmetic

• differential equations

• nonlinear systems, and

• many special functions

Page 9: Matlab Basics MEE

9

• Available in all operating systems:

•DOS

•Windows9.x/NT

•Unix

•Macintosh

•Same syntax for all platforms

• Open system environment - access to source code

•Allows - to mix MATLAB with FORTRAN or C

Page 10: Matlab Basics MEE

10

Page 11: Matlab Basics MEE

11

Page 12: Matlab Basics MEE

12

Simple MathSimple Math» 2+2.5+106

ans =

110.5000

» 4*25 + 2^3

ans =

108

» One can use it as a calculator/scratch pad

Page 13: Matlab Basics MEE

13

MATLAB VariablesMATLAB Variables» a = 2

a =

2

»b = 3

b=

3

Page 14: Matlab Basics MEE

14

MATLAB VariablesMATLAB Variables» c = 1000;» d = 0.001;» e = a*b*c/d

e =

6000000

»

Page 15: Matlab Basics MEE

15

MATLAB VariablesMATLAB Variables

MATLAB variable are automatically MATLAB variable are automatically created created when they are initialized.when they are initialized.There are three way to initializing There are three way to initializing variable in MATLAB.variable in MATLAB. Assign data to the variable in an assignment Assign data to the variable in an assignment statement. statement.

Input data into the variable from the Input data into the variable from the keyboard.keyboard.

Read data from file.Read data from file.

Page 16: Matlab Basics MEE

16

MATLAB WorkspaceMATLAB WorkspaceTo recall the variable

» a

a =

2

»

Use arrow keys for scrolling through previous commands

Page 17: Matlab Basics MEE

17

MATLAB WorkspaceMATLAB WorkspaceList of variables in the workspace

» who

Your variables are:

a b c d e »

Page 18: Matlab Basics MEE

18

Variable Naming RulesVariable Naming Rules•Variable names are case sensitive. For example NRe and nRe are different MATLAB variables

•Variable name can contain upto 31 characters. •Start with a letter, followed by letters, numbers or underscores.

•For example: SRe_2_electrical_power2by3

Page 19: Matlab Basics MEE

19

Special VariablesSpecial Variables

ans Default variable name used f or resuts

pi Value of

inf Stands f or infi nity (e.g., 1/ 0)

NaN Stands f or Not-a-Number (e.g., 0/ 0)

i, j i = j = -1

Page 20: Matlab Basics MEE

20

To Clear a VariableTo Clear a Variable» who

Your variables are:

a b c d e » clear a;» who

Your variables are:

b c d e

Page 21: Matlab Basics MEE

21

To clear all variablesTo clear all variables» who

Your variables are:

b c d e

» clear» who»

Page 22: Matlab Basics MEE

22

Complex NumbersComplex Numbers» i

ans =

0 + 1.0000i

» c1 = 2+3i

c1 =

2.0000 + 3.0000i»

Page 23: Matlab Basics MEE

23

Mathematical Mathematical FunctionsFunctions

» x=sqrt(2)/2

x =

0.7071

» y=sin(x)

y =

0.6496»

Page 24: Matlab Basics MEE

24

Built-in FunctionsTrigonometric f unctions

sin, cos, tan, sin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh, csc, sec, cot, acsc, …

Exponential f unctions

exp, log, log10, sqrt

Complex functions

abs, angle, imag, real, conj

Rounding and Remainder f unctions

floor, ceil, round, mod, rem, sign

Page 25: Matlab Basics MEE

25

Saving & Loading Data

>> A=[2 0; 0 5];>> [M l]=eig(A);>> save data1 M l; clear all;>> who>> load data1>> who

Your variables are:

M l

Page 26: Matlab Basics MEE

26

Array Operations» x = [1 2 3 4 5 6 7 8 9 10]

x =

1 2 3 4 5 6 7 8 9 10» a = 1:2:10 Note : operator

a =

1 3 5 7 9

Page 27: Matlab Basics MEE

27

Array Operations» y = sin(x)

y =

Columns 1 through 7

0.8415 0.9093 0.1411 -0.7568 -0.9589 -0.2794 0.6570

Columns 8 through 10

0.9894 0.4121 -0.5440

Page 28: Matlab Basics MEE

28

Array Addressing» y(3)

ans =

0.1411

» y(1:5)

ans =

0.8415 0.9093 0.1411 -0.7568 -0.9589

Page 29: Matlab Basics MEE

29

Array Orientation» z = [1; 2; 3; 4]

z =

1 2 3 4 » z'

ans =

1 2 3 4

Page 30: Matlab Basics MEE

30

Array Manipulation» A = [1 2; 3 4; 5 6]

A =

1 2 3 4 5 6

» B = [1 2 3; 4 5 6];» A+B??? Error using ==> +Matrix dimensions must agree.

»

Page 31: Matlab Basics MEE

31

Array Manipulation» A*B

ans =

9 12 15 19 26 33 29 40 51

Page 32: Matlab Basics MEE

32

Significance of .» clear» A = [1 2; 3 4];» B = [1 1; 2 2];» A.*B

ans =

1 2 6 8

»

Page 33: Matlab Basics MEE

33

Significance of .» A./B

ans =

1.0000 2.0000 1.5000 2.0000

» A/BWarning: Matrix is singular to working precision.

ans =

Inf Inf Inf Inf»

Page 34: Matlab Basics MEE

34

Matrix Operations» [A B]

ans =

1 2 1 1 3 4 2 2

» ans-1

ans =

0 1 0 0 2 3 1 1

»

Page 35: Matlab Basics MEE

35

>> D = A +B>> D = A +B

D =D =

2 32 3

5 65 6

Matrix Matrix OperationsOperations

>> G= A - B>> G= A - B

G =G =

0 10 1

1 21 2

Page 36: Matlab Basics MEE

36

Matrix Operations» C = [A B]

C =

1 2 1 1 3 4 2 2

» C(1,:)

ans =

1 2 1 1

»

» C(:,2)

ans =

2 4

» C(:,2:end)

ans =

2 1 1 4 2 2

»

Page 37: Matlab Basics MEE

37

Matrix Functions» size(C)

ans =

2 4

» determ(A) ans = -2 »

» A

A =

1 2 3 4

» inv(A)

ans =

-2.0000 1.0000 1.5000 -0.5000

Page 38: Matlab Basics MEE

38

Matrix FunctionsSome functions: determ, inv, diag, triu, tril, rank, eig, size

» eig(A)

ans =

-0.3723 5.3723

Show eigshow

» [a b] = eig(A)

a =

-0.8246 -0.4160 0.5658 -0.9094

b =

-0.3723 0 0 5.3723

Page 39: Matlab Basics MEE

39

» eye(2)

ans =

1 0 0 1

» eye(2,3)

ans =

1 0 0 0 1 0

»

Other such arrays:

ones(n), ones(r, c)

zeros(n), zeros(r, c)

rand(n), rand(r,c)

Standard ArraysStandard Arrays

Page 40: Matlab Basics MEE

40

ones(3)

ans =

1 1 1 1 1 1 1 1 1

>> ones(3,2)

ans =

1 1 1 1 1 1

Standard ArraysStandard Arrayszeros(2)

ans =

0 0 0 0>> zeros (3,2)

ans =

0 0 0 0 0 0

Page 41: Matlab Basics MEE

41

Plots» x = 1:2:50;» y = x.^2;» plot(x,y)»

Page 42: Matlab Basics MEE

42

Plots» plot(x,y,'*-')» xlabel('Values of x')» ylabel('y')»

Page 43: Matlab Basics MEE

43

Relational Operators

<>

<=>===~=

Page 44: Matlab Basics MEE

44

Control Flow Statementsfor n=1:10…end

while expression…end

if expression…else...end

Page 45: Matlab Basics MEE

45

MATLAB FilesMATLAB Files

M-files Script Files Function Files

MAT-files

MEX-files

Page 46: Matlab Basics MEE

46

M FilesM Files

Useful for extending the MATLAB language for your application

Useful for automating a series of steps you need to perform many times

Internal variables are local to the function by default

Operate on data in the workspace

Can accept input arguments and return output arguments

Do not accept input arguments or return output arguments

Function M-FilesScript M-Files

M-files are ordinary ASCII (text) files having extension .m containing MATLAB commands

Page 47: Matlab Basics MEE

47

SCRIPTSSCRIPTSVariables created by scripts Variables created by scripts remains in workspace even after remains in workspace even after the execution of it.the execution of it.

Create a script file and edit it in Create a script file and edit it in MATLAB Editor called M-File MATLAB Editor called M-File EditorEditor

e.g e.g

% This is a sample Script M-file% This is a sample Script M-file

A = [ 1 2 3; 4 7 1; 9 5 0];A = [ 1 2 3; 4 7 1; 9 5 0];

[x,v] = eig(A) [x,v] = eig(A)

Page 48: Matlab Basics MEE

48

Page 49: Matlab Basics MEE

49

Note script here

Page 50: Matlab Basics MEE

50

Using Script M-files

» what

M-files in the current directory C:\WINDOWS.000\Desktop\MEE\ASSIGN-1

solu_AC_Series_Ckt

» solu_AC_Series_Ckt

Page 51: Matlab Basics MEE

51

Using Script M-files» Supply frequency in Hertz = 50Supply Volatage in Volts =230Resistance in Ohms = 10Inductance in Henry = 0.5Capacitance in Micro Farad = 1000

» save data1 P Q V I pf

This is one of the saving option of MATLAB

Page 52: Matlab Basics MEE

52

FUNCTIONSFUNCTIONS

They operate on variables of their own work space.

This is not the same , we access at the MATLAB command prompt.

Create a M-File , Save it and then call it.

You may call it to execute at command prompt or within any other function also.

Page 53: Matlab Basics MEE

53

FUNCTION M-FilesFUNCTION M-Files

Function file and Script file can call each other.Multiple functions can appear in a single function M file. [Sub function] All the sub functions follow the rules of M-files. Try to use vectorized commands. Execute the program timings.m

Page 54: Matlab Basics MEE

54

General structure of a Function M-file

function [o1,o2,...] = fun_name(i1,i2...) % This is the H1 line or first help text line % The rest of the help text... % ...% ... function body here (All MATLAB code doing the actual calculations come here) % Comments, if any.

Keyword

Output argument(s) Function name

Input argument(s)

Function definition line

Page 55: Matlab Basics MEE

55

Function M-filesfunction [maxpower,rs,rl] = maxpow(V,rs)% [Max Power , Rs , RL ] = maxpow(Voltage,Rs)clc;maxpower=0.0; range = rs/10;Rl= (rs- range/2):range/6:(rs + range/2);for i = 1:length(Rl) I(i)=V/(rs + Rl(i)); power(i)= I(i)^2*Rl(i); if power(i) > maxpower maxpower = power(i); rl=Rl(i); endend

maxpow.m

Page 56: Matlab Basics MEE

56

MAT FilesMAT FilesMAT-files are the data file format files that MATLAB uses for saving data and workspace to disk. They are machine dependent binary files. However, they can be ported to different architectures as MATLAB can sniff out the architecture information from the MAT-files. Thus a sort of machine independence is achieved with MAT-files. Whenever we want to save MATLAB Workspace or only some variables in the Workspace, we can do so by issuing the command `save filename' at the MATLAB prompt. If we leave out the filename, by default it is saved to `matlab.mat'.

Page 57: Matlab Basics MEE

57

MEX FilesMEX Files Possible to call FORTRAN and C Possible to call FORTRAN and C

subroutines from inside MATLAB as subroutines from inside MATLAB as if they are built-in functions.if they are built-in functions.

The way to do it is through what are The way to do it is through what are

called called MMATLAB ATLAB EXEXecutable files ecutable files (MEX-files).(MEX-files).

Page 58: Matlab Basics MEE

58

Why MEX-files?Why MEX-files? There is no need to rewrite long There is no need to rewrite long

preexisting C or FORTRAN code into preexisting C or FORTRAN code into M-filesM-files

Serious constraints like for-loops, Serious constraints like for-loops, which tend to slow down MATLAB which tend to slow down MATLAB can be made to run faster by can be made to run faster by recoding into C or FORTRAN and recoding into C or FORTRAN and running as MEX-filesrunning as MEX-files

Page 59: Matlab Basics MEE

59

Calling a Function» [mp rs rl] = maxpow(200,5)

mp =

2000

rs = 5rl = 5

Page 60: Matlab Basics MEE

60

Calling a FunctionYou may call your function by less number of output arguments

[mp r ] = maxpow(200,5)

mp = 2000r = 5Here r is our second argument variable

Page 61: Matlab Basics MEE

61

Polynomials

Representing Polynomials:x4 - 12x3 + 25x + 116

» P = [1 -12 0 25 116];» roots(P)

ans =

11.7473 2.7028 -1.2251 + 1.4672i -1.2251 - 1.4672i

» r = ans;

Page 62: Matlab Basics MEE

62

Polynomials from the Roots

» PP = poly(r)

PP =

1.0000 -12.0000 -0.0000 25.0000 116.0000

»

Page 63: Matlab Basics MEE

63

Polynomial Multiplication

a = x3 + 2x2 + 3x + 4b = 4x2 + 9x + 16

» a = [1 2 3 4];» b = [4 9 16];» c = conv(a,b)

c =

4 17 46 75 84 64

»

Page 64: Matlab Basics MEE

64

Recommended books• Mastering MATLAB

Duane Hanselman, Bruce LittlefieldThe MATLAB Curriculum Series, Prentice Hall Inc.

• MATLAB Programming for EngineersStephan J. ChapanThomson Publication

• Introduction to Matlab 6.0 2nd edition • Delores M. Etter• David C.Kuncicky• Doug Hull Pearson Education

•http://www.mathworks.com

Page 65: Matlab Basics MEE

65

LET’S STARTLET’S START

MMATLABATLABinging

Page 66: Matlab Basics MEE

66

THANK YOU THANK YOU

VERY MUCHVERY MUCH