basics of matlab-1.doc

Upload: soumencha

Post on 02-Mar-2016

44 views

Category:

Documents


0 download

DESCRIPTION

Matlab Book

TRANSCRIPT

Er.Soumen Chatterjee,B.Tech,M.S(USA)

MATLABA LANGUAGE OF TECHNICAL COMPUTING

ER.SOUMEN CHATTERJEEB.Tech,M.S(USA),Member of Springer Online Digital LibraryMATLABThe Matrix laboratory package referred to as Matlab was originally designed to serve as a tool for numerical computation libraries LINPACK and EISPACK that were used for dealing equations. But,it was too lengthy and hard to work on simultaneous both the softwares.Thus,MATLAB has been designed for such purpose which are:-

1. Technical computing

2. Mathematical analysis

3. System simulation,It is interactive in nature and is specifically designed to solve problems in the:-

Math and computation. Algorithm development. Data acquisition.. Modelling, simulation, and prototyping. Data analysis, exploration, and visualization. Scientific and engineering graphics. Application development, including graphical user interface building.

The Matlab software was originally developed at the University of New Mexico and Stanford University, USA in the 1970s. Mr.Jack Little and Mr.Clive Moler has soon set up a company known as mathwork.The website for math work is http://www.mathworks.in/ . The software is to spend time in learning the physical and mathematical principles of a problem and not about the software. So, what are the specialities of Matlab then any other software. The Basic differences are:- Srl NoMatlabAny other Software

1It executes one instruction at a time.It takes multiple steps , some curly braces, first bracket, semicolon and then run the program.

2By analysing partial results and based on these results, new instructions can be executed that interact with the existing information already stored in the command history or computer memory.With the result the program has to get modify and then it may have to rewritten once again depend upon the demand of the programmer.

3MATLAB is a very powerful mathematical engine with wide range of toolboxes and other tools, e.g SIMULINK. It can be used for nearly everything "on system level"The software has to be compiled first and then we can get our desired output.

4MATLAB can have simulation and graphical interfaceOther softwares needs an add ons for such a purpose.

Getting Started

For getting started first double click on to the icon Matlab 2010a and it will open.There are certain desktop tools which are useful for understanding Matlab and those are:-

Desktop Tools

The following tools are managed by the MATLAB desktop, although not all of them appear by default when you first start. If you prefer a command line interface, you can use functions to perform most of the features found in the MATLAB desktop tools. Instructions for using these function equivalents are provided with the documentation for each tool.

Command Window Run MATLAB functions.

Command History View a log of the functions you entered in the Command window, copy

them, and execute them.

Launch Pad Run tools and access documentation for all of your MathWorks products.

Current Directory Browser View MATLAB files and related files, and perform file operations

such as open, and find content.

Help Browser View and search the documentation for the full family of MATLAB products.

Workspace Browser View and make changes to the contents of the workspace.

Array Editor View array contents in a table format and edit the values.

Editor/Debugger Create, edit, and debug M-files (files containing MATLAB functions).

Other MATLAB tools and windows, such as figure windows, are not managed by the desktop.

New M File Open File Cut Paste Undo Guide Profiler Help

Copy Redo Simulink Browser Current FolderRunning Matlab Functionsa) Running Functions and Entering Variables

The prompt (>>) in the Command Window indicates that MATLAB is ready to accept input from you. When you see the >> prompt, you can enter a variable or run a function. i) A=[ 1 2 3]

A= 1 2 3

ii) >> B=[4 5 6]

B =

4 5 6iii) Writing a 2x2 matrix

A=[1 2 ; 3 4]

A =

1 2

3 4iv) A=[1 2 3;4 5 6;7 8 9]

A =

1 2 3

4 5 6

7 8 9v) A=[ 1;2;3]

A =

1

2

3vi) >> D=[1,2,3]

D = 1 2 3b) Writing Trigonometric Functions

i) x=2;ii) y=sin3x+cos3x can be written as y=sin(x)^3+cos(x)^3

iii) z=(sin4x)x can be written as z=sin(x)^4*x 0.8268Important Facts

Matlab doesnot care about spacing except when working with complex number. Numbers such as 65,000,000 can be expressed as 6.5e7.

If a mistake is made in entering an instruction, causing an error message, then the whole instruction must be retyped or reentered. No characters can be modified in the command window after the key is pressed. The retyping can be avoided by pressing the up and down key. That action repeats the last instructions and the error can then be corrected with the need of retyping.

Matlab variables names are case sensitive and in general, Aa is not equal to aA is not equal to AA is not equal to aa. Matlab reserves special variables names to represent a function or a particular constant. The reader shouldnt create variables these names.

AnsTemporary variable that stores the most recent answer.

ComputerReturens the computer type.

VersionMatlab version.

VerReturns the information about the license and version of the Matlab package

LicenseLicense information

Pi=3.14159..

Exp(1)The value of e=2.71

EpsRepresents the accuracy of floating point, the smallest possible positive number

RealminThe smallest real positive number.

Realmax The largest real positive number.

BitmaxThe largest positive integer

FlopsCounts of the floating point operations

InfRepresents infinity(1/0)

NanNon a number

I or jThe value of root(-1) denotes the imaginary part of a complex number

InputAccepts information via keyboard

DateRepresents the current date as a string.

ClockReperesents current date and time as

BeepExecutes a beep sound.

Tic,tocMeasures the time between the tic and toc as a stopwatch.

PauseStops executing a program momentarily.

Pause(n)Stops executing a program during n seconds.

Matlab performs calculations based on a last value assigned to a variable.

The command clear deletes all the variables defined by a user.

The clear command can be selective such as clear A,Aa, deleting only the indicated variables.

The command clc clears the command window, but doesnt delete the variables defined earlier.

The command clf clear the figure window.

The command whos lists the variables currently used in the workspace. Eg

>> a=magic(4)

a =

16 2 3 13

5 11 10 8

9 7 6 12

4 14 15 1

>> whos

Name Size Bytes Class Attributes

a 4x4 128 double Standard mathematical expressions are evaluated from left to right,following rules: The standard matlab algebraic symbols and some simple functions are defined. A comment statement starting with the percentage symbol( %) doesnt affect any executable Matlab instruction and cant be continued on the next line.

Multiple statements can be placed on one line when they are separated by a comma(,) or semicolon(;)

A semicolon (;) at the end of an instruction suppresses the echo, whereas a comma doesnt.

Matlab can be aborted or interrupted at any time by pressing the Ctrl and C keys simultaneously (this action aborts a running Matlab program). Matlab in general is always a case sensitive and matlab commands and functions always use lowercase characters. Matlab files with extension m are reffered as M files.

Matlab accepts two types of data files: MATLAB and ASCII files.

Workspace and Array Editor

When you issue commands like:

>> c=1:10 %Array Variable

c =

1 2 3 4 5 6 7 8 9 10

>> d=sum(c)

d =

55

Matlab creates variables names X and Y, and saves them in a part of computer memory known as workspace.You can observe the contents of the workspace by typing whos command.

Double clicking on any variable in the workspace browser window brings up the array editor which allows the user to observe and modify the information stored in the variable. Any variable on workspace can be manipulated using the array editor.

Change the values Change the Changes the dimens of array elements display format of the array

Path BrowserThe Path Browser allows you to view and modify the MATLAB search path. It allows the user to add, delete, or change the order of directories in the path. Make sure that the folder where you have saved your M-file exists in MATLAB Path, otherwise it wont be executed. Also, if there are more than one functions, commands or script files (M-files) with the same name, the first one found in the search path will be executed and all the others will be inaccessible. Therefore, it is extremely important not to define a variable with the same name as a standard MATLAB function or command, which will make that function inaccessible !!

Writing Simple ExpressionsUnlike many other programing languages, you need not declare the type of values a variable can take in MATLAB. For example, a variable a can take an integer value, and in the next step, you can assign the same variable a float value and in the third step, you can assign it a string and so on.>> newvar='soumennewvar = soumen

The parantheses () are used in complex operations. Other braces( such as {} and []) are reserved for special purposes in Matlab.Here are some examples.

Mathematical ExpressionsMatlab Code

1. x + 2y 3 (y-x)

x + 2*y 3* (y-x)

2. 2 x3 + 5/x5

2*x^3 + 5/x^5

3. 5 x1/3 + 9 y0.173

5*x^(1/3) + 9*y^(0.173)

4. 3 tan(x)/ (1+ sin2(x))3*tan (x) / (1+(sin(x))^2)

5. 5 x3+sin3x-cosx35*x^3+sin^3*x-cos*x^3

6. 2x4+cos5x-sin3 (x3 +tan4x2*x^4+cos^5*x

Exercise 1: Use MATLAB to make the following calculations, for given values of x and check the results with the help of a calculator:

y = ( 1 1/x3)-1,x = 2

y = 3. x2, x = 3

y = 7(x1/3) + 4x0.58, x = 20

y = elog(x), x = 3

Exercise 2: Given an expression: f = x + 2 {y 3 (z-t)}, explain with the reasoning what are the problems with the following codes in MATLAB:

f = x + 2 {y 3 (z-t)}

f = x + 2*[y 3 (z-t)]

f = x + 2 (y 3 (z-t))

f = x + 2*(y 3 (z-t))

Subsequently, write the correct code for the expression and compute it with the values x = 2, y = 3, z = 5 and t = 7.

Matrices and ArraysMatlab works with only a single object type, the matlab array. All matlab variables, including scalars, vectors, matrices etc. are stored as matlab arrays.When the array has only one dimension ( either a row or a column) it is known as a vector, while two or more dimensional array is known as matrix.It is important to know that in matlab even a scalar is treated as an array with dimension 1x1. A character string is also treated as an array.>> A1=[1 2 3 4 5] %A1 is a vector.A1 =

1 2 3 4 5>> A2=[1 2 3 4 5] %A2 is a vector%

A2 =

1 2 3 4 5>> B=[1 4 7;2 5 8;3 6 9] %B is a matrix%B =

1 4 7

2 5 8

3 6 9The elements of a vector or a matrix are accessed using parentheses operator. Inside the parentheses is the index of the element.

>> A1(2)

ans =

2>> B(1,3)

ans =

7The length of a vector can be determined by length command, whereas the order of a matrix is determined using size command.

>> A=[1 2 3 4 5]

A =

1 2 3 4 5>> length(A)

ans =

5

>> B=[1 4 7;2 5 8;3 6 9]

B =

1 4 7

2 5 8

3 6 9

>> size(B)

ans =

3 3>> C= 'Sitaram' C =

Sitaram

>> length(C) ans =

7 >> C='Soumen'

C =

Soumen

>> length(C)

ans =

6

>> C(length(C)-2) %equivalent to writing >>c(7-2)

ans =

m

>> C(end)

ans =

n You can also access the last element in a vector using end variable as shown below:-

>> C(end) % Access the last element

ans =

nColon OperatorAnother important way to create vectors is to use the colon notation (:). This is especially useful if the vector elements are to be uniformly spaced. A general method to create a vector V is as follows:V = s:d:fwhere,s= start or initial valued= increment/decrement step f= end or final valueThe vector V then contains elements [s s+ds+2d s+3d s+kd] where k is chosen such that s+kd less than or equal to f. The following examples illustrate the use of colon operator as:->> E=1:10:100

E =

1 11 21 31 41 51 61 71 81 91>> G=1:2:10

G =

1 3 5 7 9>> X = 2*pi:-pi/2:-2*pi----------------------------colon operator exampleX =

Columns 1 through 8

6.2832 4.7124 3.1416 1.5708 0 -1.5708 -3.1416 -4.7124

Column 9

-6.2832When increment/decrement step d is omitted, MATLAB assumes d=1.Following are some examples using the colon operator to generate vectors:

V = s:d:f>> E=1:10

E =

1 2 3 4 5 6 7 8 9 10>> C=20:30

C =

20 21 22 23 24 25 26 27 28 29 30The Magic Function

MATLAB actually has a built-in function that creates magic squares of almost any size. Not surprisingly, this function is named magic:

>> A=magic(4)

A =

16 2 3 13

5 11 10 8

9 7 6 12

4 14 15 1>> D=magic(3)

D =

8 1 6

3 5 7

4 9 2

>> F=magic(2)

F =

1 3

4 2>> G=magic(5)

G =

17 24 1 8 15

23 5 7 14 16

4 6 13 20 22

10 12 19 21 3

11 18 25 2 9ConcatenationIt is the process of joining small matrices to make bigger ones. In fact, you made your first matric by concatenating its invidudual elements, The pair of square brackets [ ] is the concatenation operator. As for example the 4-by-4 magic square A and form can be written as:->> A=magic(4)---------------------------------example 1A =

16 2 3 13

5 11 10 8

9 7 6 12

4 14 15 1

>> B=[A A+32;A+48 A+16]----------------------------example 1B =

16 2 3 13 48 34 35 45

5 11 10 8 37 43 42 40

9 7 6 12 41 39 38 44

4 14 15 1 36 46 47 33

64 50 51 61 32 18 19 29

53 59 58 56 21 27 26 24

57 55 54 60 25 23 22 28

52 62 63 49 20 30 31 17Another important way to create uniformly separated elements in a vector by linspace commands.Linspace Commands

>>linspace(x1, x2, n) generates n points between two numbers x1 and x2. For n < 2, linspace returns x2. Such as the equal distance between the two points will be of X2 for eg>> Q=linspace(100,20,9)

Q =

100 90 80 70 60 50 40 30 20Logspace Commands

Y = logspace(x1,x2,n) In this case, the first element of the resultant array y, is 10x1 , the last element is 10x2 and the total number of element is n. The following are the examples:-

>> R=logspace(1,5,5)

R =

10 100 1000 10000 100000Creating Sub matrices of a given matrix>> Y=[1 3 5;2 4 6;11 9 7;3 4 5]

Y =

1 3 5

2 4 6

11 9 7

3 4 5>> Y(3,1)

ans =

11>> Y(2,3)

ans =

6>> Y(2,4)

??? Index exceeds matrix dimensions.A(2,4) results in an error because the matrix A has only 3 columnsDeleting the rows and columnDeleting the rows

>> Y(2 ,:)=[ ] % This expression implies that the 1st row of the matrix gets the new value as a nullvector i.e first row is eliminated.Y =

1 3 5

11 9 7

3 4 5Deleting the column

>> Y(:,2)=[ ]

Y =

1 5

2 6

11 7

3 5If you want to get all the elements in one single column . Then, the procedure:-

>> Y=[1 3 5;2 4 6;11 9 7;3 4 5]

Y =

1 3 5

2 4 6

11 9 7

3 4 5

>> Y(:)

ans =

1

2

11

3

3

4

9

4

5

6

7

5Insert any new element into the matrix as such:->> Y(3,2)=2

Y =

1 3 5

2 4 6

11 2 7

3 4 5

>> Y(2,4)=8

Y =

1 3 5 0

2 4 6 8

11 2 7 0

3 4 5 0Creating some special matricesThere are some special commands like ones,zeros and eye in Matlab creates special matrices. These are especially usefull for intialzing all the elements of matrix to a particular value. Let us say you want to create a matrix with all of its elements initialized to a value 3.>> A=3*ones(2,4) % creates a 2 x 4 matrix containing 3 as elements

A =

3 3 3 3

3 3 3 3Similarly you can create a matrix with all of its elements initialized to zero with another special functioms zeros:>> B=zeros(3)

B =

0 0 0

0 0 0

0 0 0Identity Matrix

An Identity matrix of order 3x3 can be created using eye command as shown next:

>> C=eye(3)

C =

1 0 0

0 1 0

0 0 1In many applications such as neural network/fuzzy logic/ Image processing there is a requirements of random number generation.The command rand generates a matrix with randomly generated numbers chosen from a uniform distribution on the interval (0.0, 1.0)

>> D=rand(2,4)

D =

0.8147 0.1270 0.6324 0.2785

0.9058 0.9134 0.0975 0.5469We can also place two matrices side by side which call as Augmented Matrices>> F=4*ones(2,2)

F =

4 4

4 4

>> H=ones(2,2)

H =

1 1

1 1

>> H=eye(2,2)

H =

1 0

0 1

>> J=[F;H]

J =

4 4

4 4

1 0

0 1

>> J=[F H]

J =

4 4 1 0

4 4 0 1OperatorsThe Matrix operators can be divided into three different categories.

(a) Matrix operators for general use.

(b) Relational Operators.

(c) Logical Operators

SymbolOperationExampleAnswer

+AdditionZ=4+2Z=6

-SubtractionZ=4-2Z=2

/Right DivisionZ=4/2Z=2

\Left DivisionZ=4\2Z=2

*MultiplicationZ=4*2Z=8

^ExponentiationZ=sqrt(4)Z=16

Function such as sqrt,.logSquare root log 2Z=log 2(4)Z=2

The order of precedence for these operators is as follows:

^/\*+-

The order of precedence can be modified by using the parenthesis ( ) which gets the highest priority

You can apply scalar multiplication, addition, substraction and power operators on a vector and matrices using the above examples.

(A) Matrix Operators

>> A=[1 2 3 4 5]

A =

1 2 3 4 5

>> B=A+2

B =

3 4 5 6 7>> C=[2 3 4]*(2+3^2)

C =

22 33 44>> P=[1 2;3 4]

P =

1 2

3 4

>> F=P^2

F =

7 10

15 22>> A=[2 3 4]-[1 2 3] %substraction of two vectors are possible of equal length

A =

1 1 1

>> A=[2 3 4]-[1 3] %substraction of two vectors are not possible of unequal length

??? Error using ==> minus

Matrix dimensions must agree.Transpose of a matrix>> B=[1 2 3;4 5 6;7 8 9]

B =

1 2 3

4 5 6

7 8 9>> B'

ans =

1 2 3

4 5 6

7 8 9>> sum(B')'

ans =

12

15

18To measure a diagonal

>> diag(B')

ans =

1

5

9For matrices using complex number the transpose command holds good for them to handle with precision.

>> K=[2+3i,2-3i;1+i,1-i]

K =

2.0000 + 3.0000i 2.0000 - 3.0000i

1.0000 + 1.0000i 1.0000 - 1.0000i

>> K'

ans =

2.0000 - 3.0000i 1.0000 - 1.0000i

2.0000 + 3.0000i 1.0000 + 1.0000i A comment can be put on matlab instructions using percentage symbol(%) doesnt affect any executable MATLAB instruction, and cant be continued on the next line.A= [1 3 4 5] %No.of elements in A%B= [2 4 1 1] %No. of elements in B%C=A+B %Addition of two numbers% Multiple statements can be placed on one olne when they are separated by a comma(,) or semicolon(;).>> D=[1,2,3,4]

D =

1 2 3 4

>> x=[1;2;3;4]

x =

1

2

3

4Matrix Multiplication and Inversion

>> A=magic(2)

A =

1 3

4 2

>> B=3*ones(2,2)

B =

3 3

3 3

>> A*B

ans =

12 12

18 18

>> B*A

ans =

15 15

15 15Backslash or left matrix divide \:If A and B are two matrices, A\B is the matrix division of A into B, which is roughly the same as (Inverse of A)B , except it is computed in a different way. X = A\B is the solution to the equation A*X = B computed by Gaussian elimination. In other words, using backslash operator, you can quickly solve many equations. For Left DivisionThe Left division is used to solve the matrix equation Ax=B where x and B are column vectors. Multiplying both sides of this equation by the inverse of A , A-1 , we have

A-1 Ax= A-1 B

Ix=x= A-1 B

Hence, x= A-1 B

So, we can write:- x=A\B.

For Right DivisionThe right division is used to solve the matrix equations x A=B where x and B are row vectors. Multiplying both sides of this equation by the inverse of A, A-1, we have.

x * A A-1= B * A-1 x= B * A-1So, we can write x=B/A.>> A=[1 2;3 4]

A =

1 2

3 4

>> B=magic(2)

B =

1 3

4 2

>> C=A\B

C =

2.0000 -4.0000

-0.5000 3.5000

Slash or right matrix divide /: If A and B are two matrices, A/B is the matrix division of B into A. A/B is roughly the same as A(Inverse of B).

>> A=[1 2;3 4]

A =

1 2

3 4

>> B=magic(2)

B =

1 3

4 2

>> C=A/B

C =

0.6000 0.1000

1.0000 0.5000

You can verify that A/B is approximately equal to A(Inverse of B) as shown below:>> G=inv(B)

G =

-0.2000 0.3000

0.4000 -0.1000

>> H=A*G

H =

0.6000 0.1000

1.0000 0.5000Array Operations

Most of the operators discussed above (such as *, ^ or /), if preceded by a dot (.) result in an element by element operation (also known as array operators) . Accordingly these operators known as array operators.

Array Multiplication

>> L=[1 2 3]

L =

1 2 3

>> M=[2 3 4]

M =

2 3 4

>> G=L.*M %It is using element by element matrix multiplication

G =

2 6 12

>> G=L*M

??? Error using ==> mtimes

Inner matrix dimensions must agree.

Array Power>> G=L.^M

G =

1 8 81>> G=L^M

??? Error using ==> mpower

Inputs must be a scalar and a square matrix.

Array / or \ Division>> G=L./M

G =

0.5000 0.6667 0.7500>> G=L/M

G =

0.6897

You can even divide a scalar by each element of a vector or a matrix as shown below:

>> G=12./L

G =

12 6 4>> G=12/L

??? Error using ==> mldivide

Matrix dimensions must agree.(B)Relational OperatorsThese are the operators where we can assure of certain conditions those are necessary for our decision making. The Boolean (or relational) operators are such conditions those are used for decision-making. A positive number (usually 1) represents TRUE and zero represents FALSE. For example:->> A=3;B=4; %Where A and B are pre assigned elements used for comparison.

>> C=A>B

C =

0 %The case is 0 because it is a false case.>> C=B>A

C =

1 %The case is 1 because it is a true case.The table below depict such occasion where it proofs the operation between such cases. Please understand that the x=1 stands for the conditions which can be true and X=0 stands where the conditions are false.

When Matrices are used with the relational operators, the size of the matrices should be the same. The comparison is made on an element by element basis(an array operation) for matrices and vectors. Consider the following examples:

>> [1 2]==[1 3]

ans =

1 0>> [1 2 3;3 5 6]>[0 4 3;1 3 7] %comparison is based upon element by element

ans =

1 0 0

1 1 0For complex numbers:-

>> (1+10i)> abs(1+10i)> 'raman'=='samir'

ans =

0 1 1 0 0>> 'chetan'=='soumen'

ans =

0 0 0 0 0 1>> 'raman'=='soumen' ??? Error using ==> eq

Matrix dimensions must agree.

These comparisons are useful in arranging the names in alphabetical order, verifying login and password and many other similar purposes.(C)Logical Operators

The relational operators may be combined with logical operators , which are:-Symbol Operation & And | or ~ not

The order of precedence for these logical operators is as follows: ~ & |

INPUTOUTPUT

ABAND A&BOR A!BXOR(A,B)NOT ~ANOT~B

0000011

0101110

1001101

1111000

>> a=8>6 & 'c'> 'b'

a =

1>> u=2>3|(1+2i)> A = [1 4 9];

B = [2 2 5];

C = [0 5 2];

d = A>B & A>C

d =

0 0 1

>> A>B

ans =

0 1 1

>> A>C

ans =

1 0 1Properties of Matrix>> A = [3*eye(2), 2*ones(2); 2*ones(2), 3*eye(2)]

A =

3 0 2 2

0 3 2 2

2 2 3 0

2 2 0 3>> size(A) %is the pair of numbers [ m n]ans =

4 4>> det(A)

ans =

-63

>> rank(A)

ans =

4Help Facilities

Type help to find a list of Matlab help topics

Shortcuts in Matlab command window.Short cuts in matlabCommand means

Alt+EnterAutofix M-Lint

Alt+LeftBack.

EnterBreak Line.

Shift+EnterBreak Line without code execution.

Ctrl+UChange to Lower Case.

Ctrl+Shift+UChange to Upper Case.

EscClear Search.

Ctrl + \Clear Selection

Ctrl+WClose

Ctrl+=Collapse All

Numpad -Collpase Tree Node

LeftCollapse or select Tree Node

Ctrl + RComment

Ctrl+CCopy

Ctrl+BCursor backward

Ctrl +HomeCursor Begin Document.

HomeCursor Begin Line

DownCursor Down

Ctrl+EndCursor End Document.

Ctrl+ECursor End Line

RightCursor Forward

Ctrl+RightCursor next Word

Ctrl+LeftCursor Previous word

UpCursor Up

Ctrl+X; Shift+DeleteCut

Ctrl+Shift+Numpad -Decrease Increment Amount

Ctrl+[Decrease Indent

Ctrl+Shift+Numpad /Decrease Multiplication Factor

Ctrl+JWrap Selected Ports

Ctrl+shift+AUpdate Ports

Ctrl+DUpdate Diagrams

BackspaceUp one level

Ctrl+Shift+UUndock

Ctrl+Z;Alt+BackspaceUndo

Ctrl+TUncomment

InsertToggle Typing Mode

TabTab

F6Switch Active File in Split Screen

Shift+F5Stop Simulation

EndStop Editing Spreadsheet

Shift+F11Step Out

F11Step in

F10Step

F5Start Simulation

Ctrl+Shift+SStart Increment Search Fwd

Ctrl+Shift+RStart Increment Serach Bwd

Ctrl+ISmart Indent

Shift+TabShift Tab

F12Set/Clear Breakpoint

Ctrl+F2Set/Clear Bookmark

Shift+UPSelection UP

Ctrl+Shift+LeftSelection Previous Word

Shift+page upSelection Page up

Shift+page downSelection Page down

Ctrl+Shift+RightSelection Next Word

Shift+RightSelection Forward

Shift+EndSelection End Line

Built in function for ArraysSome, of the built in function for arrays available in Matlab are:-

FunctionDescriptionExample

mean(A)If A is a vector, returns the mean value of the elements.>> A=[3 7 2 16];

>> mean(A)

ans =7

C=max(A)If A is a vector, C is the largest element in A.If A is a matrix,C is a row vector containing the largest element of each column of A.>> A=[3 7 2 16 9 5 18 13 0 4];

>> C=max(A) Ans=8

sum(A)If A is a vector, returns the sum of the elements of the vector>> A=[3 7 2 16];

>> sum(A) Ans=28

median(A)If A is a vector,returns the median value of the elements of the vector.>> A=[3 7 2 16];

>> median(A) Ans=5

std(A)If A is a vector, returns the standard deviation of the elements of the vector>> A=[3 7 2 16];

>> std(A) Ans=0.6377

det(A)Returns the determinant of the square matrix A.>> A=[1 2;3 4];

>> det(A) Ans=-2

dot(a,b)Calculates the scalar (dot) product of two vectors a and b. The vector can each be row or column vectors.>> a=[5 6 7];

>> b=[4 3 2];

>> dot(a,b) ans=52

cross(a,b)Calculates the cross product of two vectors a and b(axb).The two vectors must have 3 elements.>> a=[5 6 7];

>> b=[4 3 2];

>> cross(a,b)

PROBLEMS

1. Find the magnitude of the vector A (1 7 3 2).

2. Find the magnitude of the vector A (1 i 7i 3 22i).

3. Consider the numbers 1, 2, 3. Enter these as components of a column vector and as components of a row vector.

4. Given A = [1; 2; 3]; B = [4; 5; 6]; , fi nd the array product of the two vectors.

5. What command would create a 5 5 matrix with ones on the diagonal and zeros everywhere else?

6. Consider the two matrices

8 7 11 2 1 2

A 6 5- 1 B= - 1 6 4

0 2 -8 2 2 2

and compute their array product and matrix product.7. Suppose that A

1 2 3

4 5 6

7 8 9

. Use it to create B

Find a solution to the following set of equations:

x 2y 3z = 12

4x y 2z = 13

9y 8z = 1

What is the determinant of the coefficient matrix?

9. Does a solution to the following system exist? What is it?

x 2y 3z = 1

x 4y 3z = 2

2x 8y z =

10. Use LU decomposition to fi nd a solution to the system:

x 7y 9z = 12

x y 4z = 16

x y-7z = 1611. Consider the two matrices:

A = 1 0 1

2 3 4

-1 6 7B =

7 4 2

3 5 6

-1 2 1Using Matlab, determine the following:

a) A+B.

b) AB.

c) A2.

d) AT.

e) B-1.

f) BTAT.

g) A2+B2-AB.

h) detA,detB,ordetAB.

Help in Matrix Elementary math functions and their command type or command meaning Trigonometric.

sin - Sine.

sind - Sine of argument in degrees.

sinh - Hyperbolic sine.

asin - Inverse sine.

asind - Inverse sine, result in degrees.

asinh - Inverse hyperbolic sine.

cos - Cosine.

cosd - Cosine of argument in degrees.

cosh - Hyperbolic cosine.

acos - Inverse cosine.

acosd - Inverse cosine, result in degrees.

acosh - Inverse hyperbolic cosine.

tan - Tangent.

tand - Tangent of argument in degrees.

tanh - Hyperbolic tangent.

atan - Inverse tangent.

atand - Inverse tangent, result in degrees.

atan2 - Four quadrant inverse tangent.

atanh - Inverse hyperbolic tangent.

sec - Secant.

secd - Secant of argument in degrees.

sech - Hyperbolic secant.

asec - Inverse secant.

asecd - Inverse secant, result in degrees.

asech - Inverse hyperbolic secant.

csc - Cosecant.

cscd - Cosecant of argument in degrees.

csch - Hyperbolic cosecant.

acsc - Inverse cosecant.

acscd - Inverse cosecant, result in degrees.

acsch - Inverse hyperbolic cosecant.

cot - Cotangent.

cotd - Cotangent of argument in degrees.

coth - Hyperbolic cotangent.

acot - Inverse cotangent.

acotd - Inverse cotangent, result in degrees.

acoth - Inverse hyperbolic cotangent.

hypot - Square root of sum of squares.

Exponential.

exp - Exponential.

expm1 - Compute exp(x)-1 accurately.

log - Natural logarithm.

log1p - Compute log(1+x) accurately.

log10 - Common (base 10) logarithm.

log2 - Base 2 logarithm and dissect floating point number.

pow2 - Base 2 power and scale floating point number.

realpow - Power that will error out on complex result.

reallog - Natural logarithm of real number.

realsqrt - Square root of number greater than or equal to zero.

sqrt - Square root.

nthroot - Real n-th root of real numbers.

nextpow2 - Next higher power of 2.

Complex.

abs - Absolute value.

angle - Phase angle.

complex - Construct complex data from real and imaginary parts.

conj - Complex conjugate.

imag - Complex imaginary part.

real - Complex real part.

unwrap - Unwrap phase angle.

isreal - True for real array.

cplxpair - Sort numbers into complex conjugate pairs.

Rounding and remainder.

fix - Round towards zero.

floor - Round towards minus infinity.

ceil - Round towards plus infinity.

round - Round towards nearest integer.

mod - Modulus (signed remainder after division).

rem - Remainder after division.

sign - Signum.

Elementary matrices and matrix manipulation.

Elementary matrices.

zeros - Zeros array.

ones - Ones array.

eye - Identity matrix.

repmat - Replicate and tile array.

linspace - Linearly spaced vector.

logspace - Logarithmically spaced vector.

freqspace - Frequency spacing for frequency response.

meshgrid - X and Y arrays for 3-D plots.

accumarray - Construct an array with accumulation.

: - Regularly spaced vector and index into matrix.

Basic array information.

size - Size of array.

length - Length of vector.

ndims - Number of dimensions.

numel - Number of elements.

disp - Display matrix or text.

isempty - True for empty array.

isequal - True if arrays are numerically equal.

isequalwithequalnans - True if arrays are numerically equal.

Matrix manipulation.

cat - Concatenate arrays.

reshape - Reshape array.

diag - Diagonal matrices and diagonals of matrix.

blkdiag - Block diagonal concatenation.

tril - Extract lower triangular part.

triu - Extract upper triangular part.

fliplr - Flip matrix in left/right direction.

flipud - Flip matrix in up/down direction.

flipdim - Flip matrix along specified dimension.

rot90 - Rotate matrix 90 degrees.

: - Regularly spaced vector and index into matrix.

find - Find indices of nonzero elements.

end - Last index.

sub2ind - Linear index from multiple subscripts.

ind2sub - Multiple subscripts from linear index.

bsxfun - Binary singleton expansion function.

Multi-dimensional array functions.

ndgrid - Generate arrays for N-D functions and interpolation.

permute - Permute array dimensions.

ipermute - Inverse permute array dimensions.

shiftdim - Shift dimensions.

squeeze - Remove singleton dimensions.

Array utility functions.

isscalar - True for scalar.

isvector - True for vector.

Special variables and constants.

eps - Floating point relative accuracy.

realmax - Largest positive floating point number.

realmin - Smallest positive floating point number.

intmax - Largest positive integer value.

intmin - Smallest integer value.

pi - 3.1415926535897....

i - Imaginary unit.

inf - Infinity.

nan - Not-a-Number.

isnan - True for Not-a-Number.

isinf - True for infinite elements.

isfinite - True for finite elements.

j - Imaginary unit.

why - Succinct answer.

Specialized matrices.

compan - Companion matrix.

gallery - Test matrices.

hadamard - Hadamard matrix.

hankel - Hankel matrix.

hilb - Hilbert matrix.

invhilb - Inverse Hilbert matrix.

magic - Magic square.

pascal - Pascal matrix.

rosser - Classic symmetric eigenvalue test problem.

toeplitz - Toeplitz matrix.

vander - Vandermonde matrix.

wilkinson - Wilkinson's eigenvalue test matrix. Specialized math functions.

Specialized math functions.

airy - Airy functions.

besselj - Bessel function of the first kind.

bessely - Bessel function of the second kind.

besselh - Bessel functions of the third kind (Hankel function).

besseli - Modified Bessel function of the first kind.

besselk - Modified Bessel function of the second kind.

beta - Beta function.

betainc - Incomplete beta function.

betaincinv - Inverse incomplete beta function.

betaln - Logarithm of beta function.

ellipj - Jacobi elliptic functions.

ellipke - Complete elliptic integral.

erf - Error function.

erfc - Complementary error function.

erfcx - Scaled complementary error function.

erfinv - Inverse error function.

expint - Exponential integral function.

gamma - Gamma function.

gammainc - Incomplete gamma function.

gammaincinv - Inverse incomplete gamma function.

gammaln - Logarithm of gamma function.

psi - Psi (polygamma) function.

legendre - Associated Legendre function.

cross - Vector cross product.

dot - Vector dot product.

Number theoretic functions.

factor - Prime factors.

isprime - True for prime numbers.

primes - Generate list of prime numbers.

gcd - Greatest common divisor.

lcm - Least common multiple.

rat - Rational approximation.

rats - Rational output.

perms - All possible permutations.

nchoosek - All combinations of N elements taken K at a time.

factorial - Factorial function.

Coordinate transforms.

cart2sph - Transform Cartesian to spherical coordinates.

cart2pol - Transform Cartesian to polar coordinates.

pol2cart - Transform polar to Cartesian coordinates.

sph2cart - Transform spherical to Cartesian coordinates.

hsv2rgb - Convert hue-saturation-value colors to red-green-blue.

rgb2hsv - Convert red-green-blue colors to hue-saturation-value.

(B) Graphics and Plotting

Plots are very useful tool for presenting information that include standard plots with linear axes, plots with logarithmic and semi logarithmic axes, bar and stairs plots, polar plots, 3-D contour surface and mesh plots, and many more. The plots can be formatted to have a desired appearance. The line type(solid, dashed etc.), colour and thickness can be prescribed, line markers and grid lines can be added, as well as titles and text comments. Several graphs can be plotted in the same plot and several plots can be placed on the same page.

Figure ToolbarsThe figures default toolbar provides shortcuts to commonly used features. The following picture shows the features available from the toolbar:-

Graphic Objects

Graphics objects are the basic elements used to display graphs and user interface components. These objects are organized into a hierarchy, as shown by the following diagram.

A good graph consists of properly labelled axis that includes units, a descriptive title and any relevant information about the plot.

TWO DIMENSIONAL PLOTSOne of the most important functions in Matlab is the plot function and it is also one of the easiest functions to learn and use. The basic format of the function in matlab for a linear plot is:Line PlotsThe Line plot command with plot(x,y) is the basic of two-dimensional plots. The simplest form of the command is:

It helps to plot the elements of vector (or matrix) X on the horizontal axis of a figure, and the elements of vector (or matrix) Y on the vertical axis of the figure.1) >> X=[1 2 3 5 7 7.5 8 10];

>> Y=[2 6.5 7 7 5.5 4 6 8];

>> plot(X,Y) 2) Given a formula y=3x+7 with a limits of 0,10.

>> x=0:0.1:10;

>> y=3*x+7;

>> plot(x,y) 3) Draw a plot of y=cos(x) with an interval of 0 x=0:0.1:10;

>> y=cos(x);

>> plot(x,y) CLF will clear the figure at the figure window.

For 2-D Plots the basic command is plot(x,y).

A linear equation is of the form of ax+by=c, where a 0 and b 0. Its graph is a straight line and as already mentioned, only two points or ordered pairs are required.

If an equation is not linear, then the variables x and y are raised to at least the second power, and the shape of the graph is some sort of curve.

The x axis is the horizontal axis on the Cartesian plane and is refereed as the abscissa. The y axis is the vertical axis on the Cartesian plane and is referred as the ordinate.

Vectors Specifiers that define Properties with values that can be The type and color of the used to specify the line width, and

Line and markers. Markers size and edge, and fill color

Line specifiersLine stylespecifier

Solid(default) ____

Dashed ---------

Dotted :

Dash-dot -.-.-.

Line Color specifiers are:-

Line ColorSpecifier

Redr

Greeng

BlueB

CyanC

MagnetaM

YellowY

Blackk

Marker Type specifiers:-Marker typeSpecifier

Plus sign+

Circleo

Asterisk*

Point.

Squares

Diamondd

Five pointe starp

Six point starh

The specifiers are typed inside the plot command as strings.

Within the string the specifiers can be typed in any order.

The specifiers are optional. This means that none, one ,two, or all the three can be included in a command.

The command can be written as for example plot(x,y,r)

Property NameProperty NameDescriptionPossible Property Values

linewidthSpecifies the width of the lineA number in units of points(default 0.5)

markersizeSpecifies the size of the markerA number in units of points.

markeredgecolorSpecifies the color of the marker, or the color of the edge line for filled markers.Color specifies from the table above, typed as a string.

MarkerfacecolorSpecifies the color of the filling for filled markersColor specifies from the table above typed, as a string.

eg the below command looks like

Plot(x,y,-mo,Linewidth,2,markersize,12,markeredgecolor,g,markerfacecolor,y)

A note about line specifies and properties:The three line specifiers, which are the style and color of the line,and the type of the marker can also be assigned with a propertyname argument followed by a propertyvalue argument.

SpecifierProperty NamePossible Property Values

Line styleLinestyleLine style specifier from the table above,typed as a string.

Line colorColorColor specifiers from the tables above, typed as a string.

MarkerMarkerMarker specifier from the table above,typed as a string.

Plot of a given data

Year1988198919901991199219931994

Sales8122022182427

>> yr=[1988:1994];

>> sle=[8 12 20 22 18 24 27];

>> plot(yr,sle,'--k*','linewidth',2,'markersize',12)

Distortion of any plotQ4) Plot command y=3.5-0.5x cos(6x) for -2x4. Using the value of x as 0.01 and 0.3

1) When x=0.01

>> x=[-2:0.01:4];

>> y=3.5.^(-0.5*x).*cos(6*x);

>> plot(x,y)

>> title('graph of signal when x=0.01')

>> xlabel('x axis')

>> ylabel('y axis')

2) When x=0.3

>> x=[-2:0.3:4];

>> y=3.5.^(-0.5*x).*cos(6*x);

>> plot(x,y)

>> xlabel('x axis')

>> ylabel('y axis')

>> title('graph of signal when x=0.3')

Q5) Generate an overlay plot for plotting three lines y1=sint,y2=t,y3=t-t3/3!+t5/5!+t7/7! 0 t 2

>> t=linspace(0,2*pi,100);

>> y1=sin(t);

>> y2=t;

>> y3=t-(t.^3)/6+(t.^5)/120-(t.^7)/5040;

>> plot(t,y1,t,y2,'-',t,y3,'o')

>> axis([0 5 -1 5])

>> xlabel('t')

>> ylabel('sin(t) approximation')

>> title('sin(t) function')

>> text(3.5,0, 'sin(t)')

>> gtext('Linear approximation')

>> gtext('4-term approximation')

Q6)Using the following functions to plot the given data:-1) r2=5 cos 3t; 0 t 2>> t=linspace(0,2*pi,200);

>> r=sqrt(abs(5*cos(3*t)));

>> polar(t,r,k*)

Q8)f=e-3t/5 cos t ; 0 t 2>> t=linspace(0,2*pi,200);

>> f=exp(-0.6*t).*sin(t);

>> stem(t,f,k*)

Q9)Generate a plot of y(x)=e-0.7x sinx , where =15rad/s and 0 x 15>> x=[0:0.1:15];

>> w=15;

>> y=exp(-0.7*x).*sin(w*x);

>> plot(x,y)

>> title('y(x)=e^-^0^.^7^xsin\omega)

>> xlabel('t')

>> title('y(x)=e^-^0^.^7^xsin\omegax')

>> xlabel('x')

>> ylabel('y')

Contour Plots:- If we have two variables x and y are embedded into same equation and the answer can be found out into third variable irrespective of range. Then we can find the solution using contour plots.

Q10) Write an equation if z=x2+y2 with a range from -3 x 3 and -3 y 3.>> [x,y]=meshgrid(-3:0.1:3,-3:0.1:3);

>> contour(x,y,x.^2+y.^2)

>> axis square

>> xlabel('x axis')

>> ylabel('y axis')

>> title('Contour Plots of x and y using meshgird command')

Q11) Write an equation for circle of radii for values of 1,5 6 for the equation.

z=x2+y2>> contour(x,y,x.^2+y.^2,[1 2 3])

>> axis square

>> xlabel('x axis')

>> ylabel('y axis')

>> title('Contour Plots of x and y without using meshgird command')

Hold on and Hold off commandsTo plot several graphs using the hold on,hold off commands, one graph is plotted first with the plot command. Then the hold on command is typed. This keeps the figure window with the first plot open, including the axis properties and formatting. Additional graphs can be added with the plot commands that are typed next. Each plot command creates a graph that is added to that figure. The hold off command stops this process. It returns the Matlab into default mode in which the plot command erases the previous plot and resets the axis properties.Q12) Plot the graph of the function y=3x3-26x+10 and its first and second derivatives where the values range from -2 x 4.>> x=[-2:0.01:4];

>> y=3*x.^3-26*x+10;

>> yd=9*x.^2-26;

>> ydd=18*x;

>> plot(x,y,'-b')

>> hold on

>> plot(x,yd,'--r')

>> hold on

>> plot(x,ydd,':k')

>> hold off

>> xlabel('values -2 to 4')

>> ylabel('yd''ydd''y')

>> title('a graph representing hold on an off commands')

Using Plots for different numbersTwo or more graphs can be created in the same plot by typing pairs of vectors inside the plot command.It is also possible to add line specifiers following each pair. For example the command:

It represents that plot y vs x with a solid blue line for first half.

It represents that plot u vs v with a dashed red line for second half.

It represents that plot h vs t with a dotted green line for third half.The axis command

When the plot(x,y) command is executed, Matlab creates axes with limits that are based on the minimum and maximum values of the elements of x an y axis. The axis command can be used to change the range and the appearance of the axes.

Set the limits of the xaxis and yaxis. The limits for x and y axis called the domain and range, respectively. X axis is the horizontal axis on the Cartesian plane. Y axis is the ordinate axis on the Cartesian plane. axis equal---- Set the same scale for both axes.

axis square---- Set the axes region to be square.

The grid command

grid on-----Add grid lines to the plot.

grid off----Removes grid lines from the plot.Statistical PlotMatlab can also be useful for the statistics where each command can be helpful in generation of different graphs. Such, as:-

Q13) If the yr=[1988:1994] and sales represented by sle=[8 12 20 22 18 24 27] then the different graphs plotted as:-

a) Bar graph>> yr=[1988:1994];

>> sle=[8 12 20 22 18 24 27];

>> bar(yr,sle,'k')

>> xlabel('year')

>> ylabel('sales per year')

>> title('bar graph between sales and year')

b) Bar graph in horizontal

>> yr=[1988:1994];

>> sle=[8 12 20 22 18 24 27];

>> barh(yr,sle,'k')

>> xlabel('sales per year')

>> ylabel('year')

>> title('bar graph in horizontal between sales and year')

c) Stairs>> yr=[1988:1994];

>> sle=[8 12 20 22 18 24 27];

>> stairs(yr,sle,'r')

>> xlabel('sales per year')

>> ylabel('year')

>> title('bar graph in horizontal between sales and year')

d) Stem Plot .

>> yr=[1988:1994];

>> sle=[8 12 20 22 18 24 27];

>> stem(yr,sle,'m')

>> xlabel('year')

>> ylabel('sales per year')

>> title('Stem Plot can be use for Sampling frequency also')

e) Pie Chart

>> yr=[1988:1994];

>> sle=[8 12 20 22 18 24 27];

>> pie(sle)

HistogramsThese are the statistical plots that show the distribution of the data.The overall range of a given set of data points is divided into smaller subranges, and the histogram shows how many data points are in each bin. It is a vertical bar plot in which the width of each bar is equal to the range of the corresponding bin.

Use hist(y) as the command where y=is a vector with the data points.Matlab divides the range of the data points

>> y=[58 73 73 53 50 48 56 73 73 66 69 63 74 82 84 91 93 89 91 80 59 69 56 64 63 66 64 74 63 69];

>> hist(y)>> xlabel('values of year')

>> ylabel('histogram')

>> title('Histogram plot of different year sales report')

If we want to see how many elements are in each bin.Simple use.

n=hist(y)

for example >> n=hist(y)

n =

2 3 2 7 3 6 0 3 0 4

Polar PlotsPolar coordinates in which the position of a point in a plane is defined by the angle theta and the radius to the point, are frequently used in the solution of science and engineering problems.The polar commands is used to plot functions in polar coordinates. The command has the term:

Vector Vector Specifiers that define the type and color of the

Line and markers

Where theta,radius are vectors whose elements define the coordinates of the points to be plotted.The polar command plots the point and draws the grid.Q14) Plot a function r=3 cos2(0.5 )+ for all values 0 2 >> t=linspace(0,2*pi,200);

>> r=3*cos(0.5*t).^2+t;

>> polar(t,r,--k*)

Sub PlotsMultiple plots on the same page can be created with the subplot command which has the form. Where, m times n independent subwindows, where m and n indicate that the active figure window is divided into m times n independent matrix like subwindows and p is an integer over the range.

For example if there is a subplot of (2,2,3) indicates that the figure window is divided into four subwindows (two rows by two columns) and the current plot subwindow is the third(second row by first column).Q16) Draw the subplot for various equations>> y=-2:0.1:2;

>> x=9*y.^3-26*y.^2+27;

>> subplot(3,2,1)

>> plot(x,y,'--k*')

>> x=9*y.^2+27*y;

>> subplot(3,2,2)

>> plot(x,y,'--k*')

>> x=9*y;

>> subplot(3,2,3)

>> plot(x,y,'--k*')

>> x=18*y.^2+25*y;

>> subplot(3,2,4)

>> plot(x,y,'--k*')

>> x=18*y.^3;

>> subplot(3,2,5)

>> plot(x,y,'--k*')

>> x=18*y;

>> subplot(3,2,6)

>> plot(x,y,'--k*')

Lograthimic Graphs

The main reason for using lograthimic scales is to represent data that spreads over a wide range.

Q17) Draw the semilog x, semilog y and loglog for the various values of x and y as the equation preceeds

Y=2 0.2x+10 where x ranges from 0.1 x 1000>> x=linspace(0.1,60,1000);

>> y=2.^(-0.2*x+10);

>> semilogy(x,y,k*)

>> grid on

>> x=linspace(0.1,60,1000);

>> y=2.^(-0.2*x+10);

>> semilogx(x,y,k*)

>> grid on

>> x=linspace(0.1,60,1000);

>> y=2.^(-0.2*x+10);

>> loglog(x,y,k*)

>> grid on

If a figure already exists, the plot command automatically clears the existing figure and creates a new one.The command clf clears the active figure window. The plot command with multiple arguments can be used to create multiple plots on the same graphs for eg.plot(x,y1,x,y2,x,y3.....x,yn) provided their dimensions should be same. If no color or line style is specified, the default is s solid blue or black line. Markers are used to indicate points or discrete entries. If no marker type is selected, no markers are drawn. The command colordef define the overall color composition of the figure window. The default is colordef white or colordef none. If a different color composition and background is required then use the command colordef color and specify the color according to options available.Two dimensional graphs.

Elementary X-Y graphs.

plot - Linear plot.

loglog - Log-log scale plot.

semilogx - Semi-log scale plot.

semilogy - Semi-log scale plot.

polar - Polar coordinate plot.

plotyy - Graphs with y tick labels on the left and right.

Axis control.

axis - Control axis scaling and appearance.

zoom - Zoom in and out on a 2-D plot.

grid - Grid lines.

box - Axis box.

rbbox - Rubberband box.

hold - Hold current graph.

axes - Create axes in arbitrary positions.

subplot - Create axes in tiled positions.

Graph annotation.

plotedit - Tools for editing and annotating plots.

title - Graph title.

xlabel - X-axis label.

ylabel - Y-axis label.

texlabel - Produces the TeX format from a character string.

text - Text annotation.

gtext - Place text with mouse.

Hardcopy and printing.

print - Print graph or Simulink system; or save graph to M-file.

printopt - Printer defaults.

orient - Set paper orientation.Specialized 2-D Graphs

Specialized 2-D graphs.

area - Filled area plot.

bar - Bar graph.

barh - Horizontal bar graph.

comet - Comet-like trajectory.

compass - Compass plot.

errorbar - Error bar plot.

ezplot - Easy to use function plotter.

ezpolar - Easy to use polar coordinate plotter.

feather - Feather plot.

fill - Filled 2-D polygons.

fplot - Plot function.

hist - Histogram.

pareto - Pareto chart.

pie - Pie chart.

plotmatrix - Scatter plot matrix.

rose - Angle histogram plot.

scatter - Scatter plot.

stem - Discrete sequence or "stem" plot.

stairs - Stairstep plot.

Contour and 2-1/2 D graphs.

contour - Contour plot.

contourf - Filled contour plot.

contour3 - 3-D Contour plot.

clabel - Contour plot elevation labels.

ezcontour - Easy to use contour plotter.

ezcontourf - Easy to use filled contour plotter.

pcolor - Pseudocolor (checkerboard) plot.

voronoi - Voronoi diagram.

Specialized 3-D graphs.

bar3 - 3-D bar graph.

bar3h - Horizontal 3-D bar graph.

comet3 - 3-D comet-like trajectories.

ezgraph3 - General purpose surface plotter.

ezmesh - Easy to use 3-D mesh plotter.

ezmeshc - Easy to use combination mesh/contour plotter.

ezplot3 - Easy to use 3-D parametric curve plotter.

ezsurf - Easy to use 3-D colored surface plotter.

ezsurfc - Easy to use combination surf/contour plotter.

meshc - Combination mesh/contour plot.

meshz - 3-D mesh with curtain.

pie3 - 3-D pie chart.

ribbon - Draw 2-D lines as ribbons in 3-D.

scatter3 - 3-D scatter plot.

stem3 - 3-D stem plot.

surfc - Combination surf/contour plot.

trisurf - Triangular surface plot.

trimesh - Triangular mesh plot.

waterfall - Waterfall plot.

Volume and vector visualization.

vissuite - Visualization suite.

isosurface - Isosurface extractor.

isonormals - Isosurface normals.

isocaps - Isosurface end caps.

isocolors - Isosurface and patch colors.

contourslice - Contours in slice planes.

slice - Volumetric slice plot.

streamline - Streamlines from 2D or 3D vector data.

stream3 - 3D streamlines.

stream2 - 2D streamlines.

quiver3 - 3D quiver plot.

quiver - 2D quiver plot.

divergence - Divergence of a vector field.

curl - Curl and angular velocity of a vector field.

coneplot - 3D cone plot.

streamtube - 3D stream tube.

streamribbon - 3D stream ribbon.

streamslice - Streamlines in slice planes.

streamparticles - Display stream particles.

interpstreamspeed - Interpolate streamline vertices from speed.

subvolume - Extract subset of volume dataset.

reducevolume - Reduce volume dataset.

volumebounds - Returns x,y,z and color limits for volume data.

smooth3 - Smooth 3D data.

reducepatch - Reduce number of patch faces.

shrinkfaces - Reduce size of patch faces.

Images display and file I/O.

image - Display image.

imagesc - Scale data and display as image.

colormap - Color look-up table.

gray - Linear gray-scale color map.

contrast - Gray scale color map to enhance image contrast.

brighten - Brighten or darken color map.

colorbar - Display color bar (color scale).

imread - Read image from graphics file.

imwrite - Write image to graphics file.

imfinfo - Information about graphics file.

im2java - Convert image to Java image.

Movies and animation.

getframe - Get movie frame.

movie - Play recorded movie frames.

rotate - Rotate object about specified origin and direction.

frame2im - Convert movie frame to indexed image.

im2frame - Convert index image into movie format.

Color related functions.

spinmap - Spin color map.

rgbplot - Plot color map.

colstyle - Parse color and style from string.

ind2rgb - Convert indexed image to RGB image.

rgb2ind - Convert RGB image to indexed image.

dither - Convert image using dithering.

Solid modeling.

cylinder - Generate cylinder.

sphere - Generate sphere.

ellipsoid - Generate ellipsoid.

patch - Create patch.

surf2patch - Convert surface data to patch data.

THREE DIMENSIONAL PLOTSIt can be a useful way to present data that consists of more than 2 variables. Matlab provides various options for displaying three-dimensional data.They include, line,wirem surface,mesh plots and many other dimensional data.

Line Plot

3-D Line plot is a line that is obtained by connecting points in a 3-Dimensional place. A basic 3-D line plot can be created with the help of plot3 command.

x,y,z are the vectors Specifiers that define

of the coordinates of the the type and color of Properties that can be used to specif

points the line and markers. The line width and marker size. The three vectors with the coordinates of the data points must have the same number of elements.

The line specifiers,properties and property values are the same as in 2-D plots.

Q1) For the three coordinates

X= t sin(2t)

Y=t cos(2t)

Z=0.5 t

For plot of points for 0 t 6

>> t=0:0.1:6*pi;

>> x=sqrt(t).*sin(2*t);

>> y=sqrt(t).*cos(2*t);

>> z=0.5*t;

>> plot3(x,y,z,'--*k')

>> grid on

>> xlabel('x');

>> ylabel('y');

>> zlabel('z');

We can also write plot3 in this fashion ..>> t=-2:0.01:2;

>> plot3(cos(2*pi*t),sin(2*pi*t),t,'--*k')

>> xlabel('x')

>> ylabel('y')

>> zlabel('z')

>> Title('three variable using three different equations')

Q20) Draw the plot command for sint,cost and t itself for different values of t>> t=linspace(0,10*pi);

>> plot3(sin(t),cos(t),t,'--K*')

>> xlabel('x')

>> ylabel('y')

>> zlabel('z')

>> Title('Helix')

>> grid on

>> t=0:pi/100:2*pi;

>> x=sin(t);

>> y=sin(t-0.32);

>> z=sin(2*t);

>> plot3(x,y,z)

>> plot3(x,y,z,'--*k')

>> xlabel('x')

>> ylabel('y')

>> zlabel('z')

>> title('a simple graph of x,y and z axis')

>> grid on

>> t=linspace(0,1,100);

>> x=t;

>> y=t .^2;

>> z=t .^3;

>> plot3(x,y,z,'--*k')

>> grid on;

Mesh and Surface Plots

Matlab defines a mesh surface by the z-coordinates of points above a rectangular grid in the x-y plane. It forms a plot by joining adjacent points with straight lines. The results looks like it a fishing net with the knots at the data points.

>> x=-1:3;

>> y=1:4;

>> [x,y]=meshgrid(x,y)

x =

-1 0 1 2 3

-1 0 1 2 3

-1 0 1 2 3

-1 0 1 2 3

y =

1 1 1 1 1

2 2 2 2 2

3 3 3 3 3

4 4 4 4 4

>> mesh(x,y)

That is you dont have to type grid on at the end of each statement.

So,

X & Y is the matrix of the x& y coordinates of the x & y are the vector that divides the domains of x& yGrid points.Therefore there are two commands that are used for mesh or surf plots are

A mesh or surface plot is created with the mesh or surf commands, which have the forms: where X,Y are matrices with the coordinates of the grid and Z is a matrix with the value of z at the grid points.

The mesh plot is made of lines that connect the points. The surf plot, areas within the mesh lines are colored.

Q21)>> [X,Y]=meshgrid(-2*pi:0.1:2*pi,-2*pi:0.1:2*pi); >> Z=cos(X).*sin(Y);

>> mesh(X,Y,Z)

>>xlabel('x axis')

>> ylabel('y axis')

>> zlabel('z axis')

>> title('Mesh graph or plot')

>> [X,Y]=meshgrid(-2*pi:0.1:2*pi,-2*pi:0.1:2*pi);

>> Z=cos(X).*sin(Y);

>> mesh(X,Y,Z)

>> surf(X,Y,Z)

>> xlabel('x axis')

>> ylabel('y axis')

>> zlabel('z axis')

>> title('Surf graph or plot')

Q22)

>> [X,Y]=meshgrid(-2:0.1:2);

>> Z=Y.*exp(-X.^2-Y.^2);

>> mesh(X,Y,Z)

>> xlabel('x axis')

>> ylabel('y axis')

>> zlabel('z axis')

>> title('Mesh Plots for equations')

>> [X,Y]=meshgrid(-2:0.1:2);

>> Z=Y.*exp(-x.^2-y.^2);

>> surf(X,Y,Z)

>> xlabel('x axis')

>> ylabel('y axis')

>> zlabel('z axis')

>> title('Surf Plots for equations')

For above equations we can plot the functions using a shaded surface plot.This is done by using surf or surfc.The colours used are proportional to the surface heights at a given point.

For the moment we can use surfl------------( remember l is a small L not I----eye. It gives the appearance of a three-dimensional illuminated object. Use this option ifyou would like a three-dimensional plot without the mesh lines shown in the other figures.

Q23)

>> [X,Y]=meshgrid(-2:0.1:2);

>> Z=Y.*exp(-X.^2-Y.^2);

>> surfl(X,Y,Z)

>> shading Interp

>> color mapgray;

>> xlabel('x axis')

>> ylabel('y axis')

>> zlabel('z axis')

>> title('Illuminated Surf Plots for equations')

Let us generate a useful cylinder using surf command.where we can use the function as :-

Q24)

1+sin(t) for the values of 0 t 2>> t=0:pi/10:2*pi;

>> [X,Y,Z]=cylinder(1+sin(t));

>> surf(X,Y,Z)

>> axis square

>> xlabel('x axis')

>> ylabel('y axis')

>> zlabel('z axis')

>> title('surf command for a cylinder')

Q25)

>> x=-1:0.1:3;

>> y=1:0.1:4;

>> [X,Y]=meshgrid(x,y);

>> Z=X.*Y.^2./(X.^2+Y.^2);

>> mesh(X,Y,Z)

>> xlabel('x');

>> ylabel('y');

>> zlabel('z');

>> title('mesh group')

>> y=1:0.1:4;

>> Z=X.*Y.^2./(X.^2+Y.^2);

>> surf(X,Y,Z)

>> xlabel('x');

>> ylabel('y');

>> zlabel('z');

>> title('mesh group')

>> title('surf plots for matlab')

The plots that are created have colours that vary according to the magnitude of z. The variation in colour adds to the three-dimensional visualization of the plots. The color can be changed to be constant either by using the plot editor or by using colormap(C) command.

C is a three element vector in which the first, second and third elements specify the intensity of Red,Green and Blue (RGB) colors respectively.

C=[0 0 0] black C=[1 0 0] red C=[010] green C=[0 0 1]blue C=[1 1 0]yellow

C=[1 0 1]magneta C=[0.5 0.5 0.5]grey.

When the mest command executes, the gird is on by default. The grid can be off by command grid off.

A box can be drawn around the plot with the box on command.Q26) Draw the various examples for z=1.8 -1.5 x2+y2 sin(x)cos(0.5y) over the domain of -3 x 3 & -3 y 3.

>> x=-3:0.25:3;

>> y=-3:0.25:3;

>> [X,Y]=meshgrid(x,y);

>> Z=1.8.^(-1.5*sqrt(X.^2+Y.^2)).*cos(0.5*Y).*sin(X);

>> contour3(X,Y,Z,15)

>> xlabel('x axis')

>> ylabel('y axis')

>> zlabel('z axis')

>> title('Contour plots for x, y and z')

Plot a Sphere

It returns the x,y, and z coordinates of a unit sphere with 20 faces.

>> [X,Y,Z]=sphere(20);

>> surf(X,Y,Z)

Plot a cylinder

>> t=linspace(0,pi,20);

>>r=1+sin(t);

>>[X,Y,Z]=cylinder(r);

>>surf(X,Y,Z)

Plot a 3D Bar GraphFor any values of Y we can have a bar graph with bar3 as its asset.>> Y=[1 6.5 7;2 6 7;3 5.5 7;4 5 7;3 4 7;2 3 7;1 2 7];

>> bar3(Y)

3-D Stem Plot

>> t=0:0.2:10;

x=t;

y=sin(t);

z=t.^1.5;

stem3(x,y,z,'fill')

grid on

xlabel('x axis')

ylabel('y axis')

zlabel('z axis')

3-D Pie Plot>> X=[5 9 14 20];

>> explode=[0 0 1 0];

>> pie3(X,explode)

The View CommandThe view command controls the direction from which the plot is viewed. This is done by specifying a direction in terms of azimuth and elevation angles or by defining a point in space from which the plot is viewed. To set the viewing angle of the plot, the view command has the form:

z

y

eye

elevation azimuth

xaz is the azimuth, which is an angle (in degrees) in the x-y plane measured relative to the negative y axis direction and defined as positive in the counterclockwise direction.

el is the angle of elevation( in degrees) from the x-y plane. A positive value corresponds to opening an angle in the direction of the z-axis.

The default view angles are az=-37.5 degrees and el=30 degrees.Q27) For z=1.8 -1.5 x2+y2 sin(x)cos(0.5y) over the domain of -3 x 3 & -3 y 3.

>> x=-3:0.25:3;

>>y=-3:0.25:3;

>>[X,Y]=meshgrid(x,y);

>>Z=1.8.^(-1.5*sqrt(X.^2+Y.^2)).*cos(0.5*Y).*sin(X);

>>surf(X,Y,Z)

>> view(20,35)

>> xlabel('x axis')

>> ylabel('y axis')

>> zlabel('z axis')

>> title('azimuth projection of the angles')

By choosing appropriate azimuth and elevation angles the view command can be used to plot projections of 3-D plots on various planes according to the following table.

Projection Planeaz valueel value

x-y(top view)090

x-z(side view)00

y-z(side view)900

As we will take example for three different projection plane for the equations as:-X= t sin(2t)

Y=t cos(2t)

Z=0.5 t

For plot of points for 0 t 6

>> t=0:0.1:6*pi;

>> x=sqrt(t).*sin(2*t);

>> y=sqrt(t).*cos(2*t);

>> z=0.5*t;

>> plot3(x,y,z,'--*k')

>> view(0,90)

>> grid on

>> xlabel('x');

>> ylabel('y');

>> zlabel('z');

>>x=-3:0.25:3;

>>y=-3:0.25:3;

>>[X,Y]=meshgrid(x,y);

>>Z=1.8.^(-1.5*sqrt(X.^2+Y.^2)).*cos(0.5*Y).*sin(X);

>> mesh(X,Y,Z)

>> view(0,0)

>> x=-3:0.25:3;

>> y=-3:0.25:3;

>> Z=1.8.^(-1.5*sqrt(X.^2+Y.^2)).*cos(0.5*Y).*sin(X);

>> surf(X,Y,Z)

>> view(90,0)

Three dimensional graphs.

Elementary 3-D plots.

plot3 - Plot lines and points in 3-D space.

mesh - 3-D mesh surface.

surf - 3-D colored surface.

fill3 - Filled 3-D polygons.

Color control.

colormap - Color look-up table.

caxis - Pseudocolor axis scaling.

shading - Color shading mode.

hidden - Mesh hidden line removal mode.

brighten - Brighten or darken color map.

colordef - Set color defaults.

graymon - Set graphics defaults for gray-scale monitors.

cmpermute - Rearrange colors in colormap.

cmunique - Eliminate unneeded colors in colormap of indexed image.

imapprox - Approximate indexed image by one with fewer colors.

Lighting.

surfl - 3-D shaded surface with lighting.

lighting - Lighting mode.

material - Material reflectance mode.

specular - Specular reflectance.

diffuse - Diffuse reflectance.

surfnorm - Surface normals.

Color maps.

hsv - Hue-saturation-value color map.

hot - Black-red-yellow-white color map.

gray - Linear gray-scale color map.

bone - Gray-scale with tinge of blue color map.

copper - Linear copper-tone color map.

pink - Pastel shades of pink color map.

white - All white color map.

flag - Alternating red, white, blue, and black color map.

lines - Color map with the line colors.

colorcube - Enhanced color-cube color map.

vga - Windows colormap for 16 colors.

jet - Variant of HSV.

prism - Prism color map.

cool - Shades of cyan and magenta color map.

autumn - Shades of red and yellow color map.

spring - Shades of magenta and yellow color map.

winter - Shades of blue and green color map.

summer - Shades of green and yellow color map.

Transparency.

alpha - Transparency (alpha) mode.

alphamap - Transparency (alpha) look-up table.

alim - Transparency (alpha) scaling

Axis control.

axis - Control axis scaling and appearance.

zoom - Zoom in and out on a 2-D plot.

grid - Grid lines.

box - Axis box.

hold - Hold current graph.

axes - Create axes in arbitrary positions.

subplot - Create axes in tiled positions.

daspect - Data aspect ratio.

pbaspect - Plot box aspect ratio.

xlim - X limits.

ylim - Y limits.

zlim - Z limits.

Viewpoint control.

view - 3-D graph viewpoint specification.

viewmtx - View transformation matrix.

rotate3d - Interactively rotate view of 3-D plot.

Camera control.

campos - Camera position.

camtarget - Camera target.

camva - Camera view angle.

camup - Camera up vector.

camproj - Camera projection.

High level camera control.

camorbit - Orbit camera.

campan - Pan camera.

camdolly - Dolly camera.

camzoom - Zoom camera.

camroll - Roll camera.

camlookat - Move camera and target to view specified objects.

cameratoolbar - Interactively manipulate camera.

High level light control.

camlight - Creates or sets position of a light.

lightangle - Spherical position of a light.

Graph annotation.

title - Graph title.

xlabel - X-axis label.

ylabel - Y-axis label.

zlabel - Z-axis label.

text - Text annotation.

gtext - Mouse placement of text.

plotedit - Experimental graph editing and annotation tools.

Hardcopy and printing.

print - Print graph or Simulink system; or save graph to M-file.

printopt - Printer defaults.

orient - Set paper orientation.

vrml - Save graphics to VRML 2.0 file.(C)Introduction to SimulinkMATLAB

Command Window

Launches the

Help Browser

Workspace Browser

shows variables defined in workspace

View or change

Current Directory

Simulink Browser

Command History windows displays previous commands

Current Directory Browser

Gives the details of the files in the current directory

Click to move window outside of desktop

Drag the separator Bar to resize the window.

MATLAB

Workspace

Matlab array editor box

This is one of the readymade matrix where you dont have to type the elements. Plus, you can practice yourself with the help of such matix for your own learning in Matlab

This Method particularly useful in designing plots or graphics in 2d and 3d format.

Here addition of 2 changed the matrix elements but not the dimensions.

As you can see the element by element multiplication is possible once the dot is in place. But, if the dot is not there then element by element multiplication is out of question..

What is an Array?

An array is a systematic arrangement of objects, usually in rows and columns.If you use it in anywhere it will be array.As such, if no.of students in class and divided into three groups E1,E2,E3 then these are called as ARRAY.

Matrix dimension should agree with no of characters are there in the words for both left and right hand side. Any misbalance in that will be provided with an error.

Enable Plot Edit Mode

Insert Legend

Insert Colorbar

Zoom IN/OUT

Data Cursor

Hide/Display Plots

PAN

Rotate 3-D

Plot (X, Y)

Vector

Plot(x, y, Line specifiers, property name, property value)

Line specifiers:dashed red line and asterisk marker

Property name and property value:the line width is 2 points and the markers size is 12 point.

Type command

help graph2d

Type

help specgraph

Type

help specgraph

Type

help specgraph

Here the range of x and y are same which varies from -3 to 3. Thus, we needed to use meshgrid command

plot (x, y, -b , u, v,- -r , t, h , g: )

axis([xmin, xmax, ymin, ymax])

polar ( theta, radius , line specifiers )

subplot(m,n,p)

Plot3(x,y,z,Line specifiers,Property name,property value)

This is a semilogy where the function f(x)=k(a)bx

And if the x axis is linear and y axis is lograthimic,the plot f(x) v/s x is linear.

This is a semilogx returns the plot of y v/s x where the x axis scale is logarthimic but the y axis is linear.

The Matlab command loglog(x,y) returns the plot of y v/s x where both the axes scales are lograthimic.

Vector

Root

Figure

UI Objects

Axes

Hidden Annotating Axes

Core Objects

Plot Objects

Group Objects

Annotating Objects

[ X,Y]=meshgrid(x,y)

mesh(X,Y,Z)

surf(X,Y,Z)

Here we are using the command shading faceted,thus we are having different fishnet type of graph

Here we are using the command shading interp ,thus we are having different a good graph.

View(az,el) or view([az,el])

For projection 0,90

For projection 0,0

For projection (90,0)

4