Sie sind auf Seite 1von 69

Er.Soumen Chatterjee,B.Tech,M.



B.Tech,M.S(USA),Member of Springer Online Digital Library


Er.Soumen Chatterjee,B.Tech,M.S(USA)
The 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 . 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 No 1 2

It executes one instruction at a time. By 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. MATLAB 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" MATLAB can have simulation and graphical interface

Any other Software

It takes multiple steps , some curly braces, first bracket, semicolon and then run the program. 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. The software has to be compiled first and then we can get our desired output. Other 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.

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

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.
Workspace Browser shows variables defined in workspace

Launches the Help Browser

MATLAB Command Window View or change Current Directory

Simulink Browser

Drag the separator Bar to

Click to move window outside of desktop

New M File Open File Cut

Command History windows displays previous commands Paste Undo Guide Profiler Help

Current Directory Browser Gives the details of the files in the current directory



Simulink Browser

Current Folder

Running Matlab Functions

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

Er.Soumen Chatterjee,B.Tech,M.S(USA) ii) A= 1 2 3 >> B=[4 5 6] B= 4 iii) 5 6

Writing a 2x2 matrix A=[1 2 ; 3 4] A= 1 3 2 4


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


A=[ 1;2;3] A= 1 2 3


>> D=[1,2,3]

D= 1 2 3 b) Writing Trigonometric Functions i) ii) iii) x=2; y=sin3x+cos3x can be written as y=sin(x)^3+cos(x)^3 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 <enter> 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. Ans Computer Temporary variable that stores the most recent answer. Returens the computer type. 4

Version Ver License Pi Exp(1) Eps Realmin Realmax Bitmax Flops Inf Nan I or j Input Date Clock Beep Tic,toc Pause Pause(n)

Er.Soumen Chatterjee,B.Tech,M.S(USA) Matlab version. Returns the information about the license and version of the Matlab package License information =3.14159.. The value of e=2.71 Represents the accuracy of floating point, the smallest possible positive number The smallest real positive number. The largest real positive number. The largest positive integer Counts of the floating point operations Represents infinity(1/0) Non a number The value of root(-1) denotes the imaginary part of a complex number Accepts information via keyboard Represents the current date as a string. Reperesents current date and time as Executes a beep sound. Measures the time between the tic and toc as a stopwatch. Stops executing a program momentarily. 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 5 11 9 7 4 14 3 13 10 8 6 12 15 1 Bytes Class Attributes

>> whos Name Size

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 5

Er.Soumen Chatterjee,B.Tech,M.S(USA) When you issue commands like: >> c=1:10 c= 1 2 3 >> 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 MATLAB of array elements display format of the array Workspace 4 5 6 7 8 %Array Variable 9 10

Matlab array editor box

Path Browser The 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 Expressions 6

Er.Soumen Chatterjee,B.Tech,M.S(USA) Unlike 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='soumen newvar = 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 Expressions Matlab Code 1. x + 2y 3 (y-x) x + 2*y 3* (y-x) 2. 2 x3 + 5/x5 3.

2*x^3 + 5/x^5 5*x^(1/3) + 9*y^(0.173) 3*tan (x) / (1+(sin(x))^2) 5*x^3+sin^3*x-cos*x^3

1/3 + 9 y0.173

4. 3 tan(x)/ (1+ sin2(x)) 5. 5 x3+sin3x-cosx3

6. 2x4+cos5x-sin3 (x3 +tan4x 2*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 Arrays Matlab 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 = 1 2 3 4 5 %A2 is a vector% %A1 is a vector.

>> A2=[1 2 3 4 5] A2 =

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

5 %B is a matrix%

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

The 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 = 7 The 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 >> length(A) ans = 5 4 5

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

>> size(B) ans =

3 3

>> C= 'Sitaram' C = 8

Er.Soumen Chatterjee,B.Tech,M.S(USA) Sitaram >> length(C) ans = 7 >> C='Soumen' C= Soumen >> length(C) ans = 6 >> C(length(C)-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) ans = n Colon Operator Another 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: % Access the last element %equivalent to writing >>c(7-2)

V = s:d:f where, s= start or initial value d= increment/decrement step f= end or final value The vector V then contains elements [s s+d s+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

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

>> G=1:2:10 G= 1 3 5 7 9
This Method particularly useful in designing plots or graphics in 2d and 3d format.

>> X = 2*pi:-pi/2:-2*pi----------------------------colon operator example X= Columns 1 through 8 6.2832 Column 9 -6.2832 When 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 4.7124 3.1416 1.5708 0 -1.5708 -3.1416 -4.7124

>> C=20:30 C= 20 21 22 23 24 25 26 27 28 29 30

The 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 5 11 9 7 4 14 3 13 10 8 6 12 15 1
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

>> D=magic(3)

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

D= 8 3 4 1 5 9 6 7 2

>> F=magic(2) F= 1 4 3 2

>> G=magic(5) G= 17 23 4 10 11 24 1 8 15 5 7 14 16 6 13 20 22 12 19 21 3 18 25 2 9

Concatenation It 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 1 A= 16 2 5 11 9 7 4 14 3 13 10 8 6 12 15 1

>> B=[A A+32;A+48 A+16]----------------------------example 1 B= 16 2 3 5 11 10 9 7 6 4 14 15 64 50 51 53 59 58 57 55 54 52 62 63 13 8 12 1 61 56 60 49 48 37 41 36 32 21 25 20 34 43 39 46 18 27 23 30 35 42 38 47 19 26 22 31 45 40 44 33 29 24 28 17

Another important way to create uniformly separated elements in a vector by linspace commands. Linspace Commands

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

>>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 Logspace Commands 50 40 30 20

Y = logspace(x1,x2,n) In this case, the first element of the resultant array y, is 10 x1 , 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 100000

Creating Sub matrices of a given matrix

>> Y=[1 3 5;2 4 6;11 9 7;3 4 5] Y= 1 2 11 3 3 4 9 4 5 6 7 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 columns Deleting the rows and column Deleting the rows >> Y(2 ,:)=[ ] % This expression implies that the 1 st row of the matrix gets the new value as a nullvector i.e first row is eliminated. Y= 1 11 3 9 5 7

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

Deleting the column >> Y(:,2)=[ ] Y= 1 2 11 3 5 6 7 5

If 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 2 11 3 >> Y(:) ans = 1 2 11 3 3 4 9 4 5 6 7 5 Insert any new element into the matrix as such:>> Y(3,2)=2 Y= 1 2 3 4 5 6

3 4 9 4

5 6 7 5

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

11 3

2 4

7 5

>> Y(2,4)=8 Y= 1 2 11 3 3 4 2 4 5 6 7 5 0 8 0 0

Creating some special matrices There 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) A= 3 3 3 3 3 3 3 3 % creates a 2 x 4 matrix containing 3 as elements

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

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

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

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

D= 0.8147 0.9058 0.1270 0.9134 0.6324 0.0975 0.2785 0.5469

We 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 1 0 4 4 0 1

>> J=[F H] J= 4 4 4 4 1 0 0 1

Operators The Matrix operators can be divided into three different categories. (a) Matrix operators for general use. (b) Relational Operators. (c) Logical Operators


+ / \ * ^
Function such as sqrt,.log

Operation Addition Subtraction Right Division Left Division Multiplication Exponentiation Square root log 2

Er.Soumen Chatterjee,B.Tech,M.S(USA) Example Answer Z=4+2 Z=6 Z=4-2 Z=4/2 Z=4\2 Z=4*2 Z=sqrt(4) Z=log 2(4) Z=2 Z=2 Z=2 Z=8 Z=16 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= 1 2 3

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

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

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

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 4 7 >> B' ans = 1 4 7 2 5 8 3 6 9 2 5 8 3 6 9

>> sum(B')' ans = 12 15 18 To measure a diagonal >> diag(B') ans = 1 5 9 For 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 1.0000 + 1.0000i >> K'

2.0000 - 3.0000i 1.0000 - 1.0000i

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

ans = 2.0000 - 3.0000i 2.0000 + 3.0000i 1.0000 - 1.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 4 Matrix Multiplication and Inversion >> A=magic(2) A= 1 4 3 2

>> B=3*ones(2,2) B= 3 3 >> A*B ans = 12 18 12 18


3 3

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

>> B*A ans = 15 15 15 15

Backslash 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 Division The 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 Division The 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-1 So, we can write x=B/A. >> A=[1 2;3 4] A= 1 3 2 4

>> B=magic(2) B= 1 4 3 2

>> C=A\B C= 2.0000 -4.0000 -0.5000 3.5000


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

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 3 2 4

>> B=magic(2) B= 1 4 3 2

>> C=A/B C= 0.6000 1.0000 0.1000 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 1.0000 0.1000 0.5000

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

What is an Array? An array is a systematic arrangement of objects, usually 20 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.

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

>> M=[2 3 4] M= 2 3 4 %It is using element by element matrix multiplication

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

>> G=L.*M 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 >> 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


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

Matrix dimensions must agree.

(B)Relational Operators
These 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; >> C=A>B C= 0 >> C=B>A C=

%Where A and B are pre assigned elements used for comparison.

%The case is 0 because it is a false case.

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

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

For complex numbers:>> (1+10i)<(2+i) ans = 1 In the last example, the first complex number proves to be smaller than the second number. The reason is that any logical operator in MATLAB compares only the real parts in case of complex numbers. If the comparison of the magnitude is required, it should be : >> abs(1+10i)<abs(2+i) ans = 0 The relational operators work excellent with the character string data. However, the matrix length or dimensions must agree >> 'raman'=='samir' ans = 0 1 1 0 0

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

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.

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


INPUT A B 0 0 0 1 1 0 1 1 >> a=8>6 & 'c'> 'b' a= 1 >> u=2>3|(1+2i)<2 u= 1

AND A&B 0 0 0 1

OR A!B 0 1 1 1

Er.Soumen Chatterjee,B.Tech,M.S(USA) OUTPUT XOR(A,B) NOT ~A NOT~B 0 1 1 1 1 0 1 0 1 0 0 0

The relation operator can also be applied to vectors or matrices of equal dimensions as shown in the example below: >> 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 1

Properties 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 %is the pair of numbers [ m n]

>> size(A)

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

ans = 4 4 >> det(A) ans = -63 >> rank(A) ans = 4 Help Facilities Type help to find a list of Matlab help topics Shortcuts in Matlab command window.


Short cuts in matlab

Alt+Enter Alt+Left Enter Shift+Enter Ctrl+U Ctrl+Shift+U Esc Ctrl + \ Ctrl+W Ctrl+= Numpad Left Ctrl + R Ctrl+C Ctrl+B Ctrl +Home Home Down Ctrl+End Ctrl+E Right Ctrl+Right Ctrl+Left Up Ctrl+X; Shift+Delete Ctrl+Shift+Numpad Ctrl+[ Ctrl+Shift+Numpad / Ctrl+J Ctrl+shift+A Ctrl+D Backspace Ctrl+Shift+U Ctrl+Z;Alt+Backspace Ctrl+T Insert Tab F6 Shift+F5

Command means
Autofix M-Lint Back. Break Line. Break Line without code execution. Change to Lower Case. Change to Upper Case. Clear Search. Clear Selection Close Collapse All Collpase Tree Node Collapse or select Tree Node Comment Copy Cursor backward Cursor Begin Document. Cursor Begin Line Cursor Down Cursor End Document. Cursor End Line Cursor Forward Cursor next Word Cursor Previous word Cursor Up Cut Decrease Increment Amount Decrease Indent Decrease Multiplication Factor Wrap Selected Ports Update Ports Update Diagrams Up one level Undock Undo Uncomment Toggle Typing Mode Tab

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


Switch Active File in Split Screen Stop Simulation

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

Built in function for Arrays Some, of the built in function for arrays available in Matlab are:27

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

Function mean(A) C=max(A) sum(A) median(A) std(A) det(A) dot(a,b)

Description If A is a vector, returns the mean value of the elements. 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. If A is a vector, returns the sum of the elements of the vector If A is a vector,returns the median value of the elements of the vector. If A is a vector, returns the standard deviation of the elements of the vector Returns the determinant of the square matrix A. Calculates the scalar (dot) product of two vectors a and b. The vector can each be row or column vectors. Calculates the cross product of two vectors a and b(axb).The two vectors must have 3 elements.

>> A=[3 7 2 16]; >> mean(A) ans =7

>> A=[3 7 2 16 9 5 18 13 0 4]; >> C=max(A) Ans=8 >> A=[3 7 2 16]; >> sum(A) Ans=28 >> A=[3 7 2 16]; >> median(A) Ans=5 >> A=[3 7 2 16]; >> std(A) Ans=0.6377 >> A=[1 2;3 4]; >> det(A) Ans=-2 >> a=[5 6 7]; >> b=[4 3 2]; >> dot(a,b) ans=52 >> a=[5 6 7]; >> b=[4 3 2]; >> cross(a,b)


1. Find the magnitude of the vector A = (1 7 3 2). 2. Find the magnitude of the vector A = (1 + i 7i 3 2 2i). 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 212 A= 6 5- 1 B= - 1 6 4 0 2 -8 222 and compute their array product and matrix product. 7. Suppose that A = 123 456 789 . Use it to create B = 7 8 9 789 456 8.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? 28

Er.Soumen Chatterjee,B.Tech,M.S(USA) 9. Does a solution to the following system exist? What is it? x 2y + 3z = 1 x + 4y + 3z = 2 2x + 8y + z = 3 10. Use LU decomposition to fi nd a solution to the system: x + 7y 9z = 12 2x y + 4z = 16 x + y-7z = 16

11. Consider the two matrices: A= 1 2 -1 B= 7 3 -1 4 5 2 2 6 1 0 3 6 1 4 7

Using 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

Er.Soumen Chatterjee,B.Tech,M.S(USA) 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. 30

Er.Soumen Chatterjee,B.Tech,M.S(USA) 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. 31

Er.Soumen Chatterjee,B.Tech,M.S(USA) : - 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.

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

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.


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.


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

Figure Toolbars The figures default toolbar provides shortcuts to commonly used features. The following picture shows the features available from the toolbar:PAN
Rotate 3-D Insert Colorbar Insert Legend

Enable Plot Edit Mode Graphic Objects


Data Cursor

Hide/Display Plots

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.


Figure 34

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

UI Objects


Hidden Annotating Axes

Core Objects

Plot Objects

Group Objects

Annotating Objects

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


One 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 Plots The Line plot command with plot(x,y) is the basic of two-dimensional plots. The simplest form of the command is:
Vector Plot (X, Y) 35 Vector

Er.Soumen Chatterjee,B.Tech,M.S(USA) 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<10. Take the values of x for different values such as 1,0.1and 0.01 a) For x=0.1 As the values of x=0.1 the graphs will be sharper from the axis as the 0.1 will synthesize the values for y=cos(x). >> x=0:0.1:10; >> y=cos(x); >> plot(x,y)


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

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.

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


Specifiers that define The type and color of the Line and markers.

Properties with values that can be used to specify the line width, and Markers size and edge, and fill color

Line specifiers Line style Solid(default) Dashed Dotted Dash-dot Line Color specifiers are:Line Color Red Green Blue Cyan Magneta Yellow Black Marker Type specifiers:specifier ____ ---------

-.-.-. Specifier r g B C M Y k


Er.Soumen Chatterjee,B.Tech,M.S(USA) Marker type Plus sign Circle Asterisk Point Square Diamond Five pointe star Six point star Specifier + o

. s d p h

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 Name Property Name linewidth markersize markeredgecolor Markerfacecolor Description Specifies the width of the line Specifies the size of the marker Specifies the color of the marker, or the color of the edge line for filled markers. Specifies the color of the filling for filled markers Possible Property Values A number in units of points(default 0.5) A number in units of points. Color specifies from the table above, typed as a string. Color 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. Specifier Line style Line color Marker Property Name Linestyle Color Marker Possible Property Values Line style specifier from the table above,typed as a string. Color specifiers from the tables above, typed as a string. Marker specifier from the table above,typed as a string.

Plot of a given data Year Sales 1988 8 1989 12 1990 20 1991 22 1992 18 1993 24 1994 27

>> yr=[1988:1994]; >> sle=[8 12 20 22 18 24 27]; >> plot(yr,sle,'--k*','linewidth',2,'markersize',12)

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


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

Line specifiers:dashed red line and asterisk marker

Distortion of any plot Q4) 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')


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

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


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

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


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

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 Here the range of x and >> xlabel('x axis') y are same which varies >> ylabel('y axis') from -3 to 3. Thus, we >> title('Contour Plots of x and y using meshgird command') needed to use meshgrid 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')


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

Hold on and Hold off commands To 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 numbers 43

Er.Soumen Chatterjee,B.Tech,M.S(USA) Two 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:

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

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 Plot Matlab 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 axis([xmin, xmax, ymin,

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


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

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


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

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)

Histograms 46

Er.Soumen Chatterjee,B.Tech,M.S(USA) These 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 points hist(y) as the command where y=is a vector with the data points.Matlab divides the range of the data

>> 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 Plots Polar 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: polar ( theta, specifiers ) Vector radius , line


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 47

Er.Soumen Chatterjee,B.Tech,M.S(USA) >> t=linspace(0,2*pi,200); >> r=3*cos(0.5*t).^2+t; >> polar(t,r,--k*)

Sub Plots Multiple 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. subplot(m,n,p)

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


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

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

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.

>> x=linspace(0.1,60,1000); >> y=2.^(-0.2*x+10); >> semilogx(x,y,k*) >> grid on


Er.Soumen Chatterjee,B.Tech,M.S(USA) 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.

>> x=linspace(0.1,60,1000); >> y=2.^(-0.2*x+10); >> loglog(x,y,k*) >> grid on

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

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.


Er.Soumen Chatterjee,B.Tech,M.S(USA) 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 zoom grid box rbbox hold axes subplot Control axis scaling and appearance. Zoom in and out on a 2-D plot. Grid lines. Axis box. Rubberband box. Hold current graph. Create axes in arbitrary positions. Create axes in tiled positions.

Type command help graph2d

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

Type help specgraph

Er.Soumen Chatterjee,B.Tech,M.S(USA) 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. 52

Type help specgraph

Er.Soumen Chatterjee,B.Tech,M.S(USA) 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. Type help specgraph



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

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

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

x,y,z are the vectors of the coordinates of the points

Specifiers that define the type and color of the line and markers.

Properties that can be used to specif 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')

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

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

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

>> 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 -1 -1 0 0 0 1 1 1 2 2 2 3 3 3

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

-1 y= 1 2 3 4

1 2 3 4

1 2 3 4

1 2 3 4

1 2 3 4

>> mesh(x,y)

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

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

X & Y is the matrix of the x& y coordinates of the

Grid points.

x & y are the vector that divides the domains of x& y

Therefore there are two commands that are used for mesh or surf plots are mesh(X,Y,Z) surf(X,Y,Z)

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

Er.Soumen Chatterjee,B.Tech,M.S(USA) >> 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')


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

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

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

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

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


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

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

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


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

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 1]magneta C=[1 0 0] red C=[010] green C=[0.5 0.5 0.5]grey. C=[0 0 1]blue C=[1 1 0]yellow

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 62

Er.Soumen Chatterjee,B.Tech,M.S(USA) 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 Graph For 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)


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

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

Er.Soumen Chatterjee,B.Tech,M.S(USA) The 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: View(az,el) or view([az,el]) z y eye elevation azimuth x

az 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 3D plots on various planes according to the following table. 65

Er.Soumen Chatterjee,B.Tech,M.S(USA)
Projection Plane x-y(top view) x-z(side view) y-z(side view) az value 0 0 90 el value 90 0 0

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

For projection 0,90

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

For projection 0,0

>> x=-3:0.25:3; 66

Er.Soumen Chatterjee,B.Tech,M.S(USA) >> 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)

For projection (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 caxis shading hidden brighten colordef graymon cmpermute cmunique imapprox Lighting. surfl lighting material specular diffuse surfnorm Color maps. hsv hot gray bone copper - Color look-up table. - Pseudocolor axis scaling. - Color shading mode. - Mesh hidden line removal mode. - Brighten or darken color map. - Set color defaults. - Set graphics defaults for gray-scale monitors. - Rearrange colors in colormap. - Eliminate unneeded colors in colormap of indexed image. - Approximate indexed image by one with fewer colors.

- 3-D shaded surface with lighting. - Lighting mode. - Material reflectance mode. - Specular reflectance. - Diffuse reflectance. - Surface normals. - Hue-saturation-value color map. - Black-red-yellow-white color map. - Linear gray-scale color map. - Gray-scale with tinge of blue color map. - Linear copper-tone color map. 67

Er.Soumen Chatterjee,B.Tech,M.S(USA) pink white flag lines colorcube vga jet prism cool autumn spring winter summer - Pastel shades of pink color map. - All white color map. - Alternating red, white, blue, and black color map. - Color map with the line colors. - Enhanced color-cube color map. - Windows colormap for 16 colors. - Variant of HSV. - Prism color map. - Shades of cyan and magenta color map. - Shades of red and yellow color map. - Shades of magenta and yellow color map. - Shades of blue and green color map. - 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 camtarget camva camup camproj - Camera position. - Camera target. - Camera view angle. - Camera up vector. - 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. 68

Er.Soumen Chatterjee,B.Tech,M.S(USA) 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 Simulink