Top Banner

of 312

MATLAB Short Notes

Jun 03, 2018

Download

Documents

Junaid Sheikh
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/12/2019 MATLAB Short Notes

    1/312

    1

    by

    R. N. PATEL,

    Ph. D., IIT DelhiProfessor and Coordinator IIPC

    Shri Sankaracharya College of Engineering& Technology, Bhilai

  • 8/12/2019 MATLAB Short Notes

    2/312

    WELCOME !

    Dr. R.N. Patel, email: [email protected] 2

    Session-1

    Introduction to MATLAB

  • 8/12/2019 MATLAB Short Notes

    3/312

    What is Matlab?

    Matlab is basically a high level language whichhas many specialized toolboxes for makingthings easier for us

    How high?

    Assembly

    High LevelLanguages such as

    C, Pascal etc.

    Matlab

    Dr. R.N. Patel, email: [email protected] 3

  • 8/12/2019 MATLAB Short Notes

    4/312

    MATLAB = MATrix LABoratory

    Official Website:www.mathworks.com , Advantages of MATLAB

    Ease of use Platform independence Predefined functions Plotting

    Disadvantages of MATLAB Can be slow Commercial software

    Dr. R.N. Patel, email: [email protected] 4

    http://www.mathworks.com/http://www.mathworks.com/
  • 8/12/2019 MATLAB Short Notes

    5/312

    What is MATLAB?MATLAB is a high-performance language for technical

    computing. It integrates computation, visualization,and programming in an easy-to-use environmentwhere problems and solutions are expressed infamiliar mathematical notation. Typical uses include:

    Math and computation Algorithm development Modeling, simulation, and prototyping Data analysis, exploration, and visualization Scientific and engineering graphics Application development, including Graphical User

    Interface building Dr. R.N. Patel, email: [email protected] 5

  • 8/12/2019 MATLAB Short Notes

    6/312

    What is MATLAB?

    MATLAB is an interactive system whose basic data element is anarray that does not require dimensioning . This allows you tosolve many technical computing problems, especially thosewith matrix and vector formulations, in a fraction of the timeit would take to write a program in a scalar non-interactive

    language such as C or Fortran.

    MATLAB features a family of application-specific solutions calledtoolboxes. Very important to most users of MATLAB,toolboxes allow you to learn and apply specialized technology.

    Toolboxes are comprehensive collections of MATLAB functions(M-files) that extend the MATLAB environment to solveparticular classes of problems. Areas in which toolboxes areavailable include signal processing, control systems, neuralnetworks, fuzzy logic, wavelets, simulation, and many others.

    Dr. R.N. Patel, email: [email protected] 6

  • 8/12/2019 MATLAB Short Notes

    7/312

    MATLAB MATLAB is the leading computational

    software for Product design and development

    Research in industry and academia Technical education

    Over 400,000 MATLAB users worldwide

    Used in over 100 countriesFor the purposes of an engineer or scientist, MATLAB has

    the most features and is the best developed program in

    its class. -IEEE Spectrum, Software Review, February 1997 Dr. R.N. Patel, email: [email protected] 7

  • 8/12/2019 MATLAB Short Notes

    8/312

    MATLAB CustomersCommercial - USAllied SignalBell HelicopterBoeing

    HarrisHoneywellLockheed/Martin

    Northrop-GrummanPratt and WhitneyRaytheon Sys. Co.SikorskyTRW

    InternationalAerospatialeAirbus ConsortiumAlenia

    British AerospaceCASADERAIAIMatraSagemSpar AerospaceSNECMA

    GovernmentAir Force (US and

    others)Canadian Space

    AgencyDoDEuropean Space

    AgencyMinistry of Def

    NASA (all facilities) Navy (US and others) NSA

    Dr. R.N. Patel, email: [email protected] 8

  • 8/12/2019 MATLAB Short Notes

    9/312

    Notable Projects Using MATLAB

    Space Maneuvering Vehicle Deep Space Probe International Space Station Next Generation Space Telescope

    I have been amazed at how MATLAB can boost ones productivity. Anything from simple analysis to complexmodeling and simulation can be done in a fraction of the

    time it would take to write your own code.

    Gregory E. Chamitoff, Ph.D.NASA, Johnson Space Center

    Dr. R.N. Patel, email: [email protected] 9

  • 8/12/2019 MATLAB Short Notes

    10/312

    The MathWorks Products

    Control

    Control SystemRobust ControlMu-AnalysisNonlinear ControlQuantitative FbackLMI ControlModel Predictive

    Simulation& Code generation

    SIMULINKStateflowReal-Time WorkshopFixed Point BlocksetRTW Ada Extension

    Signal Processing

    Signal ProcessingDSP BlocksetWaveletsCommunications

    Language

    MATLAB MATLAB Compiler

    SystemIdentification

    System ID Frequency-Domain

    System ID

    General

    Optimization SplineStatisticsSymbolic MathNAGDatabase

    Applications

    Image Processing MappingPower System Block SetFuzzy LogicFinancial ToolboxPartial Differential EqnsNeural Network

    Partners

    ADI (Beacon)dSPACE RTIVxWorks - Wind RiverSD/Fast - Symbolic DynamicsMaple V - Waterloo MapleSaber - Analogy

    ADAMS - MDIDADS - CADSI

    Teamwork - CADRE Dr. R.N. Patel, email:[email protected] 10

  • 8/12/2019 MATLAB Short Notes

    11/312

    Introduction to MATLABDesktop

    Dr. R.N. Patel, email: [email protected] 11

  • 8/12/2019 MATLAB Short Notes

    12/312

    1.1 Introduction1.2 The MATLAB Desktop

    1.2.1 The Command Window 1.2.2 The Command History Window1.2.3 Current Directory Browser1.2.4 Workspace and Array Editor1.2.5 The Help Browser1.2.6 The Edit/Debug Window1.2.7 Path Browser

    1.3 Getting Help from Command Window

    1.4 General Syntax1.5 Writing Simple Expressions1.6 Screen Display Control1.7 MATLAB Demonstrations

    1.8 How to Quit MATLAB ? Dr. R.N. Patel, email: [email protected] 12

  • 8/12/2019 MATLAB Short Notes

    13/312

    Getting Started

    To start MATLAB, double-click the icon named MATLABon your PCs desktop and the MATLAB workingenvironment pops up. This is an interactiveenvironment, i.e. , you can start entering commands

    and obtain results instantly. In the MATLABenvironment, you can see a menubar at the top ofthe screen and the command window along withsome other windows occupy the rest of the screen.In the MATLAB command window, a command can beexecuted by typing it at the MATLAB prompt ( >> )and pressing the ENTER key .

    Dr. R.N. Patel, email: [email protected] 13

  • 8/12/2019 MATLAB Short Notes

    14/312

    The MATLAB Desktop

    Dr. R.N. Patel, email: [email protected] 14

  • 8/12/2019 MATLAB Short Notes

    15/312

    The Command Window

    A user can assign values to the variables and writeexpressions at the command prompt (>>) in thecommand window and they can be executedinstantaneously. As a simple example, try

    entering the following commands and observethe results in your MATLAB command window:

    >> a = 4+3*2>> c = 24/3;>> b = a+c

    Dr. R.N. Patel, email: [email protected] 15

  • 8/12/2019 MATLAB Short Notes

    16/312

    Variables in MATLAB

    No need for types. i.e.,

    All variables are created with double precision unlessspecified and they are matrices.

    After these statements, the variables are 1x1 matrices withdouble precision

    int a;double b;float c;

    Example:>>x=5;

    >>x1=2;

    Dr. R.N. Patel, email: [email protected] 16

  • 8/12/2019 MATLAB Short Notes

    17/312

    Variables and Arrays Array : A collection of data values organized into rows and

    columns, and known by a single name.

    Row 1

    Row 2

    Row 3

    Row 4

    Col 1 Col 2 Col 3 Col 4 Col 5

    arr(3,2)

    Variables in MATLAB

    Dr. R.N. Patel, email: [email protected] 17

  • 8/12/2019 MATLAB Short Notes

    18/312

    Arrays

    The fundamental unit of data in MATLAB

    Scalars are also treated as arrays by MATLAB (1 rowand 1 column).

    Row and column indices of an array start from 1.

    Arrays can be classified as vectors and matrices .

    Variables in MATLAB

    Dr. R.N. Patel, email: [email protected] 18

  • 8/12/2019 MATLAB Short Notes

    19/312

    Vector: Array with one dimension

    Matrix: Array with more than one dimension

    Size of an array is specified by the number of rows andthe number of columns, with the number of rowsmentioned first ( For example: n x m array ).

    Total number of elements in an array is the product ofthe number of rows and the number of columns.

    Variables in MATLAB

    Dr. R.N. Patel, email: [email protected] 19

  • 8/12/2019 MATLAB Short Notes

    20/312

    MATLAB BASICS

    Variables Variable names must begin with a letter, followed by any

    combination of letters, numbers and the underscore (_)character.

    The MATLAB language is Case Sensitive: NAME, name andName are all different variables.

    Give meaningful (descriptive and easy-to-remember) namesfor the variables. Never define a variable with the samename as a MATLAB function or command.

    Dr. R.N. Patel, email: [email protected] 20

  • 8/12/2019 MATLAB Short Notes

    21/312

    Common types of MATLAB variables double: 64-bit double-precision floating-point numbers

    They can hold real, imaginary or complex numbers in therange from 10 -308 to 10 308 with 15 or 16 decimal digits.

    >> var = 1 + i ;

    char: 16-bit values, each representing a single characterThe char arrays are used to hold character strings.

    >> comment = This is a character string ;

    The type of data assigned to a variable determines the type ofvariable that is created.

    Variables in MATLAB

    Dr. R.N. Patel, email: [email protected] 21

  • 8/12/2019 MATLAB Short Notes

    22/312

    The Command History Window

    It displays a list of the commands that a user has entered in theCommand Window .The commands remain in the list until theyare deleted. A section of these commands can be selected byusing (Shift + Arrow) keys and can be executed by pressing ENTER(alternatively you can also use Copy and Paste), without typingthem again. If you wish to execute the previously executedcommands, press UP () arrow key at the command prompt.Typing the first letter/word of any previous entry, followed by anUP() arrow displays all the pervious entries beginning with thatletter/word in sequence. The command can be then re-executed

    by pressing ENTER. At your command prompt, press UP() arrowtwice or type c and press UP() arrow key once to re -execute ormodify the following statement:

    >> c = 24/3; Dr. R.N. Patel, email: [email protected] 22

  • 8/12/2019 MATLAB Short Notes

    23/312

    Dr. R.N. Patel, email: [email protected] 23

  • 8/12/2019 MATLAB Short Notes

    24/312

    Current Directory Browser

    You can set the current working directory of MATLAB by typing

    the path of a particular folder over the Current Directory

    window in the MATLAB Desktop. Alternatively, you can

    also use the icon

    to browse and set the current working directory. Then set

    the current directory to a folder where your files are

    stored. For example, C: \MATLAB6p5\ work is shown as

    current working directory in Figure 1. MATLAB would lookfor files for execution in current working directory.

    Dr. R.N. Patel, email: [email protected] 24

  • 8/12/2019 MATLAB Short Notes

    25/312

    Workspace and Array Editor

    When you issue commands like:

    >> x = 10;>> y = [1 2 3 4]; % Array variable

    MATLAB creates variables named x and y , and saves them in a part ofcomputer memory known as Workspace. The symbol % isused in MATLAB for inserting the comments for the clarity of

    the codes. Anything written after % in a line is not executed(even if it is an executable statement or expression).

    Dr. R.N. Patel, email: [email protected] 25

  • 8/12/2019 MATLAB Short Notes

    26/312

    You can observe the contents of the Workspace by typing the

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

    Dr. R.N. Patel, email: [email protected] 26

  • 8/12/2019 MATLAB Short Notes

    27/312

    Change the display formatChange the values of thearray elements

    MATLAB Array EditorWindow

    MATLAB Workspace

    Dr. R.N. Patel, email: [email protected] 27

  • 8/12/2019 MATLAB Short Notes

    28/312

    The Help Browser

    The ? icon on the MATLAB desktop launches the HelpWindow, which provides links to the documentation on allthe components (or toolboxes) for your MATLAB version. Itprovides an important and dynamic reference for workingon MATLAB.

    There is another simpler way to get help on different functionse.g. by typing

    >> help sqrt at the command prompt.

    You get the help on function sqrt.

    Dr. R.N. Patel, email: [email protected] 28

  • 8/12/2019 MATLAB Short Notes

    29/312

    Dr. R.N. Patel, email: [email protected] 29

  • 8/12/2019 MATLAB Short Notes

    30/312

    The Edit/Debug WindowThe MATLAB Editor/Debugger provides a graphical user interface for basic text

    editing, as well as for M-file debugging. The Editor/Debugger is a single toolthat can be used for editing, debugging, or both.

    The Edit/Debug Window is essentially a programming text editor, with the MATLABlanguage features highlighted in different colors. Instead of writing thecommands directly in the Command Window, a series of commands may beplaced into a file known as script file or M-file (saved with extension .m).The entire file can be executed just by typing its name (without extensionname) at the command prompt. For example, consider the following filesimple.m:

    Dr. R.N. Patel, email: [email protected] 30

  • 8/12/2019 MATLAB Short Notes

    31/312

    -----------------simple.m--------------------------------x = 10;y = x/4;z = y*9;-------------------------------------------------------------

    This can be executed in command space in thefollowing manner (assuming the file is in the currentworking directory):

    >> simple

    Dr. R.N. Patel, email: [email protected] 31

  • 8/12/2019 MATLAB Short Notes

    32/312

    Path Browser

    The Path Browser allows you to view and modify the MATLABsearch path. It allows the user to add, delete, or change theorder of directories in the path. Make sure that the folderwhere you have saved your M-file exists in MATLAB Path,

    otherwise it wont be executed. Also, if there are morethan one functions, commands or script files (M-files) withthe same name, the first one found in the search path willbe 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 orcommand, which will make that function inaccessible !!

    Dr. R.N. Patel, email: [email protected] 32

  • 8/12/2019 MATLAB Short Notes

    33/312

    Dr. R.N. Patel, email: [email protected] 33

  • 8/12/2019 MATLAB Short Notes

    34/312

    Getting Help from Command Window

    To access help from command window, type help at the MATLAB prompt

    and press ENTER. e.g.

    >> help

    >> help plot

    To search a particular topic by title, the lookfor command proves useful.For example, to find out what facility MATLAB provides on computingintegral of a function, you can give the following command:

    >> lookfor integral

    The output of this is a list of several functions that are related to integralsand contain the word integral in their help documentation.

    Dr. R.N. Patel, email: [email protected] 34

  • 8/12/2019 MATLAB Short Notes

    35/312

    Other important commands with similar purpose are:

    what : lists the MATLAB related files found inthe current working directory,

    dir : lists all files in the current working directory,

    which FUNCT : displays the full pathname of the function withthe name FUNCT.

    You can also learn how to effectively use help command by typing thefollowing:

    >> help help

    Dr. R.N. Patel, email: [email protected] 35

  • 8/12/2019 MATLAB Short Notes

    36/312

    General Syntax

    MATLAB automatically creates a variable in the memory as soon as it is

    assigned a value. The variable names must begin with a letter, followed byany combination of letters, numbers and the underscore (_ ) character.Variable names are case sensitive , in the sense that the uppercase andlowercase letters are distinguished. For example, a variable named Value is different from value and so also from vaLue . Similarly, MULT, multand Mult are three different variables.

    MATLAB requires that all variable names (except for those used by symbolictoolbox) be assigned numeric values prior to being used in an expression.For example:

    >> a=2.3;

    >> b = 4.7;>> d = c + a*b;MATLAB responds as:??? Undefined function or variable 'c'.

    Dr. R.N. Patel, email: [email protected] 36

  • 8/12/2019 MATLAB Short Notes

    37/312

  • 8/12/2019 MATLAB Short Notes

    38/312

    Special Values

    pi: value up to 15 significant digits i, j: sqrt(-1) Inf : infinity (such as division by 0) NaN : Not-a-Number (division of zero by zero)

    clock : current date and time in the form of a 6-elementrow vector containing the year, month, day, hour,minute, and second

    date : current date as a string such as 16-Feb-2004

    eps : epsilon is the smallest difference between twonumbers

    ans : stores the result of an expression

    Dr. R.N. Patel, email: [email protected] 38

  • 8/12/2019 MATLAB Short Notes

    39/312

    Several variables (or expressions) can also be defined in the same line, separated bya comma (,) or a semicolon (;). When a comma is used, the system displays thevariable and its value on the command line. For example, when you type thefollowing:

    >> x=1.1, y=3.3, z=5.5MATLAB responds with the following display:x =1.1y =

    3.3z =

    5.5

    The use of semicolons in place of the commas would suppress the outputs, e.g.

    >> x=3.5; y=1.9; z=2.75;the command window does not display the values as was done in the former case.

    Dr. R.N. Patel, email: [email protected] 39

  • 8/12/2019 MATLAB Short Notes

    40/312

    Writing Simple Expressions

    Unlike many other programing languages, you need not declare the type ofvalues a variable can take in MATLAB. For example, a variable a cantake an integer value, and in the next step, you can assign the samevariable a float value and in the third step, you can assign it a stringand so on. Here is an example:

    >> newvar = 5newvar =

    5

    >> newvar = 20.197newvar =

    20.1970

    >> newvar = 'surabhi'newvar =surabhi

    Dr. R.N. Patel, email: [email protected] 40

  • 8/12/2019 MATLAB Short Notes

    41/312

    Operators (arithmetic)

    + addition- subtraction

    * multiplication/ division^ power

    complex conjugate transpose

    Dr. R.N. Patel, email: [email protected] 41

  • 8/12/2019 MATLAB Short Notes

    42/312

    Operators (relational, logical)

    == Equal to ~= Not equal to < Strictly smaller > Strictly greater = Greater than equal to & And operator | Or operator

    Dr. R.N. Patel, email: [email protected] 42

  • 8/12/2019 MATLAB Short Notes

    43/312

    Writing Simple Expressions

    variable_name = expression ;

    addition a + b a + b

    subtraction a - b a - b multiplication a x b a * b division a / b a / b exponent a b a ^ b

    Dr. R.N. Patel, email:[email protected] 43

  • 8/12/2019 MATLAB Short Notes

    44/312

    Hierarchy of operations

    x = 3 * 2 + 6 / 2 Processing order of operations is important

    parentheses (starting from the innermost)

    exponentials (from left to right) multiplications and divisions (from left to right) additions and subtractions (from left to right)

    >> x = 3 * 2 + 6 / 2x =

    9

    Dr. R.N. Patel, email:[email protected] 44

  • 8/12/2019 MATLAB Short Notes

    45/312

    The parentheses ( ) are used in complex operations. Otherbraces (such as { } and [ ] ) are reserved for specialpurposes in MATLAB. Here are some examples ofwriting simple expressions:

    Mathematical Expression MATLAB Code

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

    2. 2 x 3 + 5/x 5

    3. 5 x 1/3 + 9 y 0.173

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

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

    2*x^3 + 5/x^5

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

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

    Dr. R.N. Patel, email:[email protected] 45

  • 8/12/2019 MATLAB Short Notes

    46/312

    Screen Display Control (The "format" function):

    MATLAB performs numeric computations in double-precision format. Thenumber of digits after the decimal of a floating point number can becontrolled by using the format command. The following code illustratesthe usage of format command:

    >> format % this is same as 'format short', the% default format

    >> pi % pi has a pre-defined value in MATLAB

    ans =3.1416

    >> format long % change the display format to long>> pians =

    3.14159265358979

    Dr. R.N. Patel, email: [email protected] 46

  • 8/12/2019 MATLAB Short Notes

    47/312

    >> format long e

    >> pi

    ans =

    3.141592653589793e+000

    >> format hex

    >> pi

    ans =

    400921fb54442d18

    Dr. R.N. Patel, email: [email protected] 47

  • 8/12/2019 MATLAB Short Notes

    48/312

    >> format compact

    >> x = 2, y = 3,

    x =

    2

    y =

    3

    This results in the values being displayed, but the display is

    compact to save your Desktop area.

    See >> help format for more details on the other display formats

    available with MATLAB.

    Dr. R.N. Patel, email: [email protected] 48

  • 8/12/2019 MATLAB Short Notes

    49/312

    Changing the data format

    >> value = 12.345678901234567;format short 12.3457format long 12.34567890123457

    format short e 1.2346e+001format long e 1.234567890123457e+001format short g 12.346format long g 12.3456789012346format rat 1000/81

    Dr. R.N. Patel, email:[email protected] 49

  • 8/12/2019 MATLAB Short Notes

    50/312

    MATLAB Demonstrations

    MATLAB is shipped with a number ofdemonstration programs. Use help demos tofind out more about these. You can also typedemo on the MATLAB prompt to enter thedemonstration programs. The number ofdemos depends upon the version of MATLAB

    that you have.

    Dr. R.N. Patel, email: [email protected] 50

  • 8/12/2019 MATLAB Short Notes

    51/312

    How to Quit MATLAB ?

    You can leave a MATLAB session by typing quitor by typing exit at the MATLAB prompt. IfMATLAB session enters into an infinite loop,you can interrupt the running of the programby a Ctrl+c command the from keyboard,and thus you would get back to the command

    prompt.

    Dr. R.N. Patel, email: [email protected] 51

  • 8/12/2019 MATLAB Short Notes

    52/312

    Summary

    help command Online help lookfor keyword Lists related commands which Version and location info clear Clears the workspace

    clc Clears the command window diary filename Sends output to file diary on/off Turns diary on/off who, whos Lists content of the workspace more on/off Enables/disables paged output Ctrl+c Aborts operation Continuation % Comments

    Dr. R.N. Patel, email: [email protected] 52

  • 8/12/2019 MATLAB Short Notes

    53/312

    ExercisesExercise 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 = 3Exercise 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 thevalues x = 2, y = 3, z = 5 and t = 7.

    Dr. R.N. Patel, email: [email protected] 53

    E i 3 Th MATLAB i i ^2(30) ^2(30) d

  • 8/12/2019 MATLAB Short Notes

    54/312

    Exercise 3: The MATLAB expression >> sin^2(30) + cos^2(30) doesnot result in expected value of 1. What are the possibleproblems with this code?

    Exercise 4: Type demo on MATLABs command prompt and thenpress ENTER to explore what it contains. Locate thedemonstration programs for 2-D plots on the same.

    Exercise 5: What are the different ways to use MATLAB help on aparticular function? Find the syntax and usage of the functionlog with MATLAB help.

    Exercise 6: Suppose you do not know what is the MATLABfunction for finding inverse of sine function. How would youget the help on it?

    Exercise 7: Use MATLAB to verify the identity e j = cos () + j sin(), taking any three values of variable .

    Dr. R.N. Patel, email: [email protected] 54

  • 8/12/2019 MATLAB Short Notes

    55/312

    Session-2Vectors, Matrices and Operators in MATLAB

    Dr. R.N. Patel, email: [email protected] 55

  • 8/12/2019 MATLAB Short Notes

    56/312

    The MATLAB ArrayCreating Vectors and Matrices

    Creating Sub Matrices of a Given MatrixChanging the Elements of a Given MatrixCreating Special MatricesConcatenation

    OperatorsMatrix OperatorsMatrix Multiplication and InversionArray operatorsRelational OperatorsLogical Operators

    Properties of a MatrixReplicating Data to Form a Matrix

    Dr. R.N. Patel, email: [email protected] 56

  • 8/12/2019 MATLAB Short Notes

    57/312

    The MATLAB Array MATLAB works with only a single object type, theMATLAB array. All MATLAB variables, includingscalars, vectors, matrices, strings, etc., are storedas MATLAB arrays. A matrix or a vector can betreated as an array according to the context.

    When the array has only one dimension (either a row

    or a column) it is known as a vector, while two ormore dimensional array is known as a matrix.It is important to note that in MATLAB even a scalar is

    treated as an array with dimension 11. Acharacter string is also treated as an array. Observethe following examples:

    Dr. R.N. Patel, email: [email protected] 57

  • 8/12/2019 MATLAB Short Notes

    58/312

    >> A1=[1,2,3,4,5] % A1 is a vector>> A2=[1 2 3 4 5] % A2 is a vector same as A1>> B=[1,4,7;2,5,8;3,6,9] % B is a matrix

    >> C= 'Sitaram' % C is a string array

    By typing the above at the command prompt, MATLAB echoes as follows:

    A1 =

    1 2 3 4 5A2 =

    1 2 3 4 5B =

    1 4 7

    2 5 83 6 9

    C =Sitaram

    Dr. R.N. Patel, email: [email protected] 58

  • 8/12/2019 MATLAB Short Notes

    59/312

    BASIC RULES

    Arrays are constructed using brackets [ ] and semicolons. All ofthe elements of an array are listed in row order.

    The values in each row are listed from left to right and they areseparated by blank spaces or commas.

    The rows are separated by semicolons or new lines.

    The number of elements in every row of an array must be thesame.

    Dr. R.N. Patel, email: [email protected] 59

  • 8/12/2019 MATLAB Short Notes

    60/312

    The elements of a vector or a matrix are accessed usingparentheses operator. Inside the parentheses is the index ofthe element. Consider the following examples:

    >> A1(2) % indicates second element of array a.ans =

    2>> B(1,3)

    ans =7

    >> C(1)ans =

    S

    Dr. R.N. Patel, email: [email protected] 60

    The length of a vector can be determined by length command whereas the

  • 8/12/2019 MATLAB Short Notes

    61/312

    The length of a vector can be determined by length command, whereas theorder of a matrix is determined using size command. Consider the previousexamples again:

    >> A=[1,2,3,4,5]A =

    1 2 3 4 5

    >> length(A) % gives the length (i.e., no. of elements) of the vector aans =

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

    1 4 72 5 83 6 9

    >> size(B) % gives the order of the given matrixans =

    3 3 Dr. R.N. Patel, email: [email protected] 61

  • 8/12/2019 MATLAB Short Notes

    62/312

    >> [m n]=size(B) % returns the number of rows and columns in b as% separate output variablesm =

    3n =

    3>> C= 'Sitaram'C =Sitaram>> length(C)ans =

    7>> C(length(C)-2) % This is equivalent to writing >> c(7-2)ans =rYou can also access the last element in a vector using end variable as shown below:>> C(end) % Access the last elementans =m

    MATLAB automatically interprets the variable end as the last element of a particular vector. Inother words, end = length(C) in relation to the above example.

    Dr. R.N. Patel, email: [email protected] 62

  • 8/12/2019 MATLAB Short Notes

    63/312

    Creating Vectors and Matrices

    A common way to create vector is to put the elements of the vector separated byspace in square brackets [ ] as shown below:

    >> VEC1 = [10 12 0 1 5 8 9 10 20]VEC1 =

    10 12 0 1 5 8 9 10 20

    Sometimes the number of vector elements could be large. In such cases, you can usethe three continuous dots ( ) to break the array in several lines. Considerthe following example showing the creation of a vector B with 12 elements:

    >> B =[1 2 3 4 ...5 6 7 8 ...9 10 11 12]B =1 2 3 4 5 6 7 8 9

    10 11 12

    Dr. R.N. Patel, email: [email protected] 63

  • 8/12/2019 MATLAB Short Notes

    64/312

    Another important way to create vectors is to use the colon notation (:). This isespecially useful if the vector elements are to be uniformly spaced. A generalmethod to create a vector V is as follows:

    V = s:d:fwhere,

    s= start or initial valued= increment/decrement stepf= end or final value

    The vector V then contains elements [s s+d s+2d s+3 d s+kd] where k is chosensuch that s+kd less than or equal to f. The following examples illustrate the useof colon operator:

    >> 1:2:10ans =

    1 3 5 7 9

    Dr. R.N. Patel, email: [email protected] 64

  • 8/12/2019 MATLAB Short Notes

    65/312

    >> X = 2*pi:-pi/2:-2*piX =Columns 1 through 76.2832 4.7124 3.1416 1.5708 0 -1.5708 -3.1416Columns 8 through 9-4.7124 -6.2832

    When increment/decrement step d is omitted, MATLAB assumes d=1.

    Following are some examples using the colon operator to generatevectors:

    >> 1:10ans =

    1 2 3 4 5 6 7 8 9 10>> Y = -pi: piY =

    -3.1416 -2.1416 -1.1416 -0.1416 0.8584 1.8584 2.8584

    Dr. R.N. Patel, email: [email protected] 65

  • 8/12/2019 MATLAB Short Notes

    66/312

    Another important way to create uniformly separated elements

    in a vector is by using the linspace command. The command

    >>linspace(x1, x2, n) generates n points between twonumbers x1 and x2. For n < 2, linspace returns x2.

    If n equally spaced values on a logarithmic scale are desired then

    you can use:Y = logspace(x1,x2,n)

    In this case, the first element of the resultant array y, is 10 x1,

    the last element is 10 x2 and the total number of elements is n.

    The following are a few examples of vector creation using

    linspace and logspace commands:

    Dr. R.N. Patel, email: [email protected] 66

  • 8/12/2019 MATLAB Short Notes

    67/312

    >> p = linspace(100, 20, 9)

    p =

    100 90 80 70 60 50 40 30 20

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

    q =

    10 100 1000 10000 100000

    Dr. R.N. Patel, email: [email protected] 67

    C i S b M i f Gi M i

  • 8/12/2019 MATLAB Short Notes

    68/312

    Creating Sub Matrices of a Given Matrix:

    MATLAB supports several ways to create and access the part of amatrix. One can access one element, a row, a column or a sub-matrix. For example:

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

    1 3 52 4 611 9 73 4 5

    The following are the different ways to create and access parts ofmatrix A:

    A(i, j) returns the (i, j) entry of the matrix A.

    Dr. R.N. Patel, email: [email protected] 68

  • 8/12/2019 MATLAB Short Notes

    69/312

    >> A(3,1) % (3rd row, 1st Column) entryans =

    11

    >> A(2,3)ans =6

    >> A(2,4)??? Index exceeds matrix dimensions.A(2,4) results in an error because the matrix A has only 3 columns.

    A(i, :) returns the ith row of A.>> A(2,:)ans =

    2 4 6A(:, j) returns the jth column of A. The output is a column vector>> A(:,3)ans =

    5675

    Dr. R.N. Patel, email: [email protected] 69

    A(2 4 1 2) f 2 4 d l f 1 2

  • 8/12/2019 MATLAB Short Notes

    70/312

    A(2 : 4, 1 : 2) returns rows from 2 to 4 and columns from 1 to 2.Thus a 32 matrix is returned as shown below:

    >> A(2 : 4, 1 : 2)

    ans =2 411 93 4

    You can also access rows 2 to rows 4 with all columns by A(2:4, :)as shown below:

    >> A(2:4,:)ans =

    2 4 611 9 73 4 5

    Dr. R.N. Patel, email: [email protected] 70

    A([2 4], :) returns rows 2 and 4 and all columns. The output is 2 3 matrix as shown

  • 8/12/2019 MATLAB Short Notes

    71/312

    A([2 4], :) returns rows 2 and 4 and all columns. The output is 2 3 matrix as shownbelow:

    >> A([2 4], :)ans =

    2 4 63 4 5

    A(:) returns one long column combining the columns of A as follows:

    >> A(:)ans =

    121133

    494567

    5 Dr. R.N. Patel, email: [email protected] 71

    Changing the Elements of a Given Matrix

  • 8/12/2019 MATLAB Short Notes

    72/312

    Changing the Elements of a Given Matrix

    Suppose a given matrix is:

    >> A = [9 1 7; 2.5 7.5 12; 5 6.2 11]A =

    9.0000 1.0000 7.00002.5000 7.5000 12.00005.0000 6.2000 11.0000

    You can change certain elements in the matrix without modifying the value ofother elements as below:

    This example illustrates how you can change one entry at a time:

    >> A(3, 2) = 7 % resets the (3, 2) entry to 7A =

    9.0000 1.0000 7.00002.5000 7.5000 12.00005.0000 7.0000 11.0000

    Dr. R.N. Patel, email: [email protected] 72

    Since the given matrix has changed now the next operation will be

  • 8/12/2019 MATLAB Short Notes

    73/312

    Since the given matrix has changed now, the next operation will beperformed over this changed matrix.

    The following examples show how you can change a row or a columnof a matrix:

    >> A(3, :) = [7 1 9] % resets the third rowA =

    9.0000 1.0000 7.00002.5000 7.5000 12.00007.0000 1.0000 9.0000

    >> A(:,1) = [1 2]??? Error

    The error in above assignment comes because of dimension mismatch.Since A(:,1) is a column vector of length 3, it can only be assigned avector that is of length 3.

    Dr. R.N. Patel, email: [email protected] 73

  • 8/12/2019 MATLAB Short Notes

    74/312

    You can also delete rows and columns by using colon operatorand an empty pair of square brackets. Consider the followingexample where 1st row of A is deleted:

    >> A(1,:)=[ ] % this expression implies that% the 1st row of the matrix gets the new

    % value as a NULL vector, i.e., 1st row is eliminated.

    A =2.5000 7.5000 12.00007.0000 1.0000 9.0000

    Dr. R.N. Patel, email: [email protected] 74

    C ti g S i l M t i

  • 8/12/2019 MATLAB Short Notes

    75/312

    Creating Special Matrices

    There are some special commands like ones, zeros, and eye in MATLAB to

    create special matrices. These are especially useful for initializing all theelements of matrix to a particular value. Let us say you want to create amatrix with all of its elements initialized to a value 3.

    >> A = 3* ones (2,4) % Creates a 2 4 matrix

    A =3 3 3 33 3 3 3

    >> A = 3 * ones(3) % Creates a 3 3 matrixA =

    3 3 33 3 33 3 3

    Dr. R.N. Patel, email: [email protected] 75

    Si il l t t i ith ll f it l t i iti li d t

  • 8/12/2019 MATLAB Short Notes

    76/312

    Similarly, you can create a matrix with all of its elements initialized tozero with another special function zeros:

    >> B = zeros(3)

    B =0 0 0

    0 0 0

    0 0 0

    An Identity matrix of order 33 can be created using eye command asshown next:

    >> C = eye (3)C =

    1 0 00 1 0

    0 0 1

    Dr. R.N. Patel, email: [email protected] 76

    I li ti lik l t k l i g t i ith d

  • 8/12/2019 MATLAB Short Notes

    77/312

    In many applications like neural network learning, a matrix with randomnumbers is required. The command rand generates a matrix withrandomly generated numbers chosen from a uniform distribution on the

    interval (0.0,1.0).

    >> D = rand (2,4)

    D =

    0.6038 0.1988 0.7468 0.93180.2722 0.0153 0.4451 0.4660

    You can create a vector using any of abovementioned commands as thefollowing example illustrates:

    >> X = rand(1,4)

    X =

    0.8913 0.7621 0.4565 0.0185

    Dr. R.N. Patel, email: [email protected] 77

    >> d = [1 3 5 7], A = diag(d)

  • 8/12/2019 MATLAB Short Notes

    78/312

    [ ], g( )d =

    1 3 5 7A =

    1 0 0 00 3 0 00 0 5 00 0 0 7

    The magic function creates a square matrix in which the sum of elements inall columns and rows and the two diagonals are equal. Consider thefollowing example:

    >> z = magic(3) % gives the following matrixz =8 1 63 5 74 9 2

    Dr. R.N. Patel, email: [email protected] 78

    Concatenation

  • 8/12/2019 MATLAB Short Notes

    79/312

    Concatenation

    Larger matrices can be formed by concatenating smaller matrices.

    The pair of square brackets, [ ], is also known as theconcatenation operator. The basic idea behind concatenation isthat two matrices A and B can be concatenated as [A B] to form alarger matrix C provided the dimensions of A and B match forconcatenation (in this case, the number of rows should be samefor both A and B).

    >> V = [-5, 2:7, 10] % V is a concatenated vector.% Note the middle vector is 2:7

    V =

    -5 2 3 4 5 6 7 10

    Dr. R.N. Patel, email: [email protected] 79

    >> A= eye(2) % A is a matrix

  • 8/12/2019 MATLAB Short Notes

    80/312

    >> A eye(2) % A is a matrix

    A =

    1 0

    0 1

    >> B = 2*ones(2) % B is a matrix

    B =

    2 2

    2 2

    >> C = [A B] % creates the augmented matrixC =

    1 0 2 2

    0 1 2 2

    Dr. R.N. Patel, email: [email protected] 80

    You can also place a matrix B below another matrix A by using C= [A;B]. This

  • 8/12/2019 MATLAB Short Notes

    81/312

    p y g ;is like an extension of semicolon (;) notation indicating a new line information of a matrix. The new matrix C would have same number ofcolumns as A and B.

    >> D = [A;B]D =

    1 00 1

    2 22 2

    >> E = [A 2*A; ones(2,2)*4 zeros(2,2)] % a concatenated matrixE =1 0 2 00 1 0 24 4 0 04 4 0 0

    Dr. R.N. Patel, email: [email protected] 81

  • 8/12/2019 MATLAB Short Notes

    82/312

    Operators The operators can be divided into three

    general categories:

    (a) Matrix operators and operatorsused in general algebra,

    (b) Relational operators and,(c) Logical operators.

    Matrix Operators The following table summarizes the

    matrix operators available inMATLAB:

    The order of precedence for these

    operators is as follows:^ / \ * + -

    The order of precedence can be modified byusing the parenthesis ( ) which gets thehighest priority

    Symbol Operation

    + Addition

    - Subtraction orNegation

    * Multiplication

    ^ Power

    ' Transpose (real) orConjugate transpose

    (complex)

    .' Transpose (real orcomplex)

    \ Left division

    / Right division

    Dr. R.N. Patel, email:

    [email protected] 82

    Y l l lti li ti dditi bt ti d

  • 8/12/2019 MATLAB Short Notes

    83/312

    You can apply scalar multiplication, addition, subtraction and

    power operators on a vector and matrices using the above

    operators. Consider the following example where you would

    like to add 2 to all the elements in vector A:

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

    A = 1 2 3 4 5 6 9 8 7

    >> B = A + 2

    B = 3 4 5 6 7 8 11 10 9

    Dr. R.N. Patel, email: [email protected] 83

    >> A * 4

  • 8/12/2019 MATLAB Short Notes

    84/312

    A 4ans =

    4 8 12 16 20 24 36 32 28>> C = [2 3 4]*(2 + 3^2)C =

    22 33 44The similar rules hold good for subtraction and division operation of an array

    with a scalar. However, when you apply power (^) with a matrix A, itimplies matrix multiplication as shown in the following example:

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

    1 23 4

    >> A^2 % MATLAB inteprets A^2 as A*Aans =7 10

    15 22

    Dr. R.N. Patel, email: [email protected] 84

  • 8/12/2019 MATLAB Short Notes

    85/312

    Another useful operator is transpose operator ('). For example, a column vectorbecomes a row vector after the transpose operation. The transpose of a matrix A is

  • 8/12/2019 MATLAB Short Notes

    86/312

    becomes a row vector after the transpose operation. The transpose of a matrix A isA'.

    >> A=[1;3;5] % creates a column matrix A

    A =135

    >> B=A' % the ' operator is used to get the row vectorB =

    1 3 5

    >> C = [1 2; 3 4; 5 6] % Create a 32 matrixC =

    1 23 4

    5 6>> D = C' % D is 23 matrixD =

    1 3 52 4 6

    Dr. R.N. Patel, email: [email protected] 86

    In case of matrices of complex numbers, the transpose operator ' gives conjugated

  • 8/12/2019 MATLAB Short Notes

    87/312

    p , p p g j gtranspose. To get non-conjugated transpose, .' operator is used.

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

    A =2.0000 + 3.0000i 2.0000 - 3.0000i 1.00001.0000 + 1.0000i 1.0000 - 1.0000i 0

    >> A' %gives conjugate transposeans =

    2.0000 - 3.0000i 1.0000 - 1.0000i2.0000 + 3.0000i 1.0000 + 1.0000i1.0000 0

    >> A.' % the dot (.) preceding (') makes it% a simple (un-conjugated) transpose

    ans =2.0000 + 3.0000i 1.0000 + 1.0000i2.0000 - 3.0000i 1.0000 - 1.0000i1.0000 0

    Dr. R.N. Patel, email: [email protected] 87

    Matrix Multiplication and Inversion

  • 8/12/2019 MATLAB Short Notes

    88/312

    p>> A = [1 2; 3 4]A =

    1 23 4

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

    2 2

    2 2Consider the matrix multiplication AB and BA as shown below:>> A*Bans =

    6 6

    14 14>> B*Aans =

    8 128 12

    Dr. R.N. Patel, email: [email protected] 88

    The two special matrix operations supported by MATLAB provide rapid

  • 8/12/2019 MATLAB Short Notes

    89/312

    The two special matrix operations supported by MATLAB provide rapidsolutions to simultaneous equations or linear regression problems. Theseoperations are:

    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 Gaussianelimination. In other words, using backslash operator, you can quicklysolve many equations.

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

    Dr. R.N. Patel, email: [email protected] 89

    >> A = [1 2; 3 4]

  • 8/12/2019 MATLAB Short Notes

    90/312

    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

    Dr. R.N. Patel, email: [email protected] 90

    >> F = A/B

  • 8/12/2019 MATLAB Short Notes

    91/312

    >> F A/B

    ans =

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

    0.4000 -0.1000

    >> H = A*G

    H =

    0.6000 0.1000

    1.0000 0.5000

    Dr. R.N. Patel, email: [email protected] 91

    Example: Solving the system of equations

  • 8/12/2019 MATLAB Short Notes

    92/312

    2x1 + 8x2 + 2x 3 = 26

    3x1 + 4x2 + 6x 3 = 126x

    1+ 2x

    2 + 4x

    3 = 14

    Solution:

    The given system of equation can be written in matrix form as:A*X = B

    Where, X = [x 1 x2 x3]' , A and B are given below

    >> A = [2 8 2; 3 4 6; 6 2 4], B = [26 12 14]'

    A =

    2 8 2

    3 4 66 2 4

    B =

    2612

    14

    Dr. R.N. Patel, email: [email protected] 92

    Example: Solving the system of equationsMethod 1:

  • 8/12/2019 MATLAB Short Notes

    93/312

    Since A*X = B, X can be written as follows:>> X = inv (A)* B % Where inv (A) is inverse of matrix A

    This computes the solution as:

    X =

    2.0000

    3.0000

    -1.0000

    Method 2:

    You can also get the solution using the backslash operator as shown below:>> X = A\B

    ans =

    2.00003.0000

    -1.0000

    You can verify the result by substituting X values into system of equations (or by multiplying

    the matrices A and X). Dr. R.N. Patel, email: [email protected] 93

    Array Operators

  • 8/12/2019 MATLAB Short Notes

    94/312

    y p

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

    operation). Accordingly, these operators are known as array operators.

    >> X = [1 2 3]X =

    1 2 3

    >> Y = [4 5 6]Y =4 5 6

    >> X .* Y % Element by element multiplicationans =

    4 10 18

    >> X * Y??? Error using ==> *Inner matrix dimensions must agree.

    Dr. R.N. Patel, email: [email protected] 94

    We can also apply array operations on power, slash and backslash operators

  • 8/12/2019 MATLAB Short Notes

    95/312

    pp y y p p , pas shown below:

    Array Power

    >> D = X.^Y % Array power

    D =

    1 32 729

    The element D(1) is formed above by X(1)^Y(1). Similarly, all the otherelements can be computed.

    Array division

    >> E= X./Y % Element by element division

    E =

    0.2500 0.4000 0.5000

    The element E(1) is formed in above command by X(1)/Y(1). All the otherelements can be computed in a similar manner.

    Dr. R.N. Patel, email: [email protected] 95

  • 8/12/2019 MATLAB Short Notes

    96/312

    Array Inverse division

    >> F = X.\Y

    F =

    4.0000 2.5000 2.0000

    The element F(1) is formed by Y(1) divided by X(1). All the other elements can becomputed in a similar manner.

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

    >> G = 12./Y

    G =

    3.0000 2.4000 2.0000

    The element G(1) is computed as 12/Y(1). The other elements can be computed in asimilar manner.

    Dr. R.N. Patel, email: [email protected] 96

    The use of . Element

  • 8/12/2019 MATLAB Short Notes

    97/312

    Operation

    K= x^2

    Erorr:??? Error using ==> mpower Matrix must be square.B=x*yErorr:??? Error using ==> mtimes Inner matrix dimensions must agree.

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

    1 2 35 1 43 2 -1

    y = A(3 ,:)

    y=3 4 -1

    b = x .* y

    b=3 8 -3

    c = x . / y

    c=0.33 0.5 -3

    d = x .^2

    d=1 4 9

    x = A(1,:)

    x=1 2 3

    Dr. R.N. Patel, email:[email protected] 97

    Relational Operators

  • 8/12/2019 MATLAB Short Notes

    98/312

    Relational Operators

    The Boolean (or relational) operators are used for decision-making. A positive

    number (usually 1) represents TRUE and zero represents FALSE. For

    example,

    >> a=3; b=7;

    >> c = b>a

    c =

    1

    >> d = a>b

    d =

    0

    Dr. R.N. Patel, email: [email protected] 98

    The relational operators in MATLAB are given in the table below:

  • 8/12/2019 MATLAB Short Notes

    99/312

    p g

    Dr. R.N. Patel, email: [email protected] 99

    When matrices are used with the relational operators, the size of thematrices should be the same The comparison is made on an element

  • 8/12/2019 MATLAB Short Notes

    100/312

    matrices should be the same. The comparison is made on an elementby 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]ans =

    1 0 01 1 0

    >> (1+10i) < (2+i)ans =

    1

    Dr. R.N. Patel, email: [email protected] 100

    In the last example, the first complex number proves to be smaller than thesecond number The reason is that any logical operator in MATLAB

  • 8/12/2019 MATLAB Short Notes

    101/312

    second number. The reason is that any logical operator in MATLABcompares only the real parts in case of complex numbers. If thecomparison of the magnitude is required, it should be :

    >> abs(1+10i) < abs(2+i)ans =

    0

    The relational operators can also be used with the string data as shown in thefollowing command:

    >> 'raman'=='samir'ans =

    0 1 1 0 0

    Such comparisons can be useful in arranging the names in alphabetical order,verifying login and password and many other similar purposes.

    Dr. R.N. Patel, email: [email protected] 101

    Logical Operators:

  • 8/12/2019 MATLAB Short Notes

    102/312

    The relational operators may be combined by logical operators, which are:

    Symbol Operation & And| Or~ Not

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

    ~ & |

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

    1>> 2>3|(1+2i)

  • 8/12/2019 MATLAB Short Notes

    103/312

    dimensions as shown in the example below:>> A = [1 4 9];

    >> B = [2 2 5];>> C = [0 5 2];>> d = A>B & A>Cd =

    0 0 1The expression d = A>B & A>C is evaluated by taking and of the two

    vector A>B and A>C, both of which are shown below:>> A>Bans =

    0 1 1>> A>Cans =

    1 0 1

    Dr. R.N. Patel, email: [email protected] 103

    Properties of a Matrix

  • 8/12/2019 MATLAB Short Notes

    104/312

    Some of the important numerical values associated with a matrix are its size,determinant value and rank.

    >> A = [3*eye(2), 2*ones(2); 2*ones(2), 3*eye(2)]A =

    3 0 2 20 3 2 22 2 3 02 2 0 3

    >> size(A) % is the pair of numbers [m n]% m is number of rows% n is columns

    ans =4 4

    >> det(A) % is the determinant (A must be a square matrix)ans =

    -63>> rank(A) % is the rank of matrix Aans =

    4

    Dr. R.N. Patel, email: [email protected] 104

    Replicating Data to Form a Matrix

  • 8/12/2019 MATLAB Short Notes

    105/312

    MATLAB provides two functions that can be used to create matrices by

    replicating a scalar, a column vector, a row vector, or a matrix somespecified number of times. These functions are useful in 2-D and 3-Dplots of a function. These two functions are: repmat and meshgrid.

    The general syntax for repmat is:>> repmat (x,r,c)Where x can be a scalar, a vector or a matrix. The function repmat will

    produce r c tiling of copies of x. Consider the following example:>> P = repmat (2.5, 2, 3)

    The above command results in the following output:

    p =2.5000 2.5000 2.50002.5000 2.5000 2.5000

    Dr. R.N. Patel, email: [email protected] 105

    >> R = repmat ([1, 2]', 2, 3) % the symbol ' indicates% transpose of vector

  • 8/12/2019 MATLAB Short Notes

    106/312

    % transpose of vectorR =

    1 1 1

    2 2 21 1 12 2 2

    The resultant matrix R is tiling of the vector [1, 2]' into two rows and threecolumns. You can also tile a matrix into any number of rows and columnsas shown in the example below:

    >> s = repmat ([3 7; 5 9], 2, 3) % produces (23) tiles of given% matrix [3 7; 5 9]

    s =

    3 7 3 7 3 75 9 5 9 5 93 7 3 7 3 75 9 5 9 5 9

    Dr. R.N. Patel, email: [email protected] 106

    Another useful command for preparing vectors for plotting is the meshgridcommand [X Y] = meshgrid (x y)

  • 8/12/2019 MATLAB Short Notes

    107/312

    command. [X,Y] = meshgrid (x,y),The rows of the output matrix X are copies of the vector x and the columns of theoutput matrix Y are copies of the vector y.

    >> x = [1 2 3 4];>> y = [5 6 7 8];>> [X Y] = meshgrid(x,y)X =

    1 2 3 41 2 3 41 2 3 41 2 3 4

    Y =5 5 5 56 6 6 6

    7 7 7 78 8 8 8

    Both X and Y are matrices of same size (44) and they make a proper combination ofcoordinates to be used for plotting purposes.

    Dr. R.N. Patel, email: [email protected] 107

  • 8/12/2019 MATLAB Short Notes

    108/312

    Thank You !

    For your Patience and Attention

    Dr. R.N. Patel, email: [email protected] 108

  • 8/12/2019 MATLAB Short Notes

    109/312

    Session-3MATLAB Graphics and Plotting

    Dr. R.N. Patel, email:[email protected] 109

    3.1 Introduction

  • 8/12/2019 MATLAB Short Notes

    110/312

    3.2 2-Dimensional Plots3.3 Plot Aesthetics

    3.3.1 Changing the Axis3.3.2 Adding Text

    3.4 Multiple Plots3.4.1 Using a Single plot Command

    3.4.2 Using Multiple plot Commands 3.5 Sub-plotting 3.6 Some Other Useful 2-D Plots3.7 Advanced Concepts on Plot Annotation and Labeling

    3.7.1 Using Handle Graphics3.7.2 An Easier Way to Plot Editing

    3.8 3-D Graphics3.9 Function Plotters`

    Dr. R.N. Patel, email: [email protected] 110

  • 8/12/2019 MATLAB Short Notes

    111/312

    2-Dimensional Plots

    One of the most important functions in MATLAB is the plotfunction 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:

    plot(X,Y)

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

    Dr. R.N. Patel, email: [email protected] 111

    Given a linear formula:

  • 8/12/2019 MATLAB Short Notes

    112/312

    y = 3x+7

    Create an m-file for plot of y versus x.

    The following lines of code create the desired plot:

    X = 0:0.1:10; % X takes the values from 1 to 10 in% interval of 0.1

    Y = 3*X + 7; % Y generates an array of values for

    % each value of X

    plot(X,Y) % plots Y values versus their X% counterparts

    Dr. R.N. Patel, email: [email protected] 112

    The color and point marker can be changed on a plot by adding a third

  • 8/12/2019 MATLAB Short Notes

    113/312

    The color and point marker can be changed on a plot by adding a thirdparameter in single quotes to the plot command. For example, to plot theabove function as a red, dotted line, the code should be changed to:

    ---------------------------------------------------------- X = 0:0.1:10;Y = 3*X + 7;plot(X,Y,'r:')

    ---------------------------------------------------------- Note that the third argument has r standing for red color and : for dotted

    lines.

    A user can select any combination of color, marker style and line style andplace it in place of string style in the following command:

    plot(X,Y, style)

    Dr. R.N. Patel, email: [email protected] 113

  • 8/12/2019 MATLAB Short Notes

    114/312

    >> X = 0:10;

    >> Y = 3*X+7;>> plot (X,Y, 'mp-.')

    This code plots a magenta (denoted by m in the

    argument) dash-dot line (denoted by -. in the

    argument) with a pentagram marker at each datapoint (denoted by p in the argument)

    Dr. R.N. Patel, email: [email protected] 114

    Plot Aesthetics

  • 8/12/2019 MATLAB Short Notes

    115/312

    Plot Aesthetics Having obtained a certain plot for the given data, its proper

    labeling and annotation is extremely important, otherwiseit becomes difficult to extract any useful information fromthe given plot.

    Changing the Axis One of the important features in clarity of a plot is proper

    selection of axes ranges. For instance, in order to plot thefunction y=exp(5t)-1, where y is the function of time t,enter the following commands at MATLAB prompt:

    >> T = 0:0.01:5;>> Y = exp(5*T)-1;>> plot(T,Y)

    Dr. R.N. Patel, email: [email protected] 115

    It is quite difficult to visualize the nature of the function for the

  • 8/12/2019 MATLAB Short Notes

    116/312

    It is quite difficult to visualize the nature of the function for thetime interval 0 to 1 sec. One option is to go back and write the

    code again for t=0 to t=1 sec. However, the better and simplerway is to use the axis command.

    >> axis([0, 1, 0, 50])

    General format:

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

    Here (xmin, xmax) and (ymin, ymax) specify the x and y axisranges, respectively.

    Dr. R.N. Patel, email: [email protected] 116

    Adding Text

  • 8/12/2019 MATLAB Short Notes

    117/312

    A title will be placed in the center and above the plot figure with the

    command:>> title('title string') The x-axis is labeled with the command:>> xlabel('x-axis string') Similarly, the y-axis is labeled with the following command:

    >> ylabel('y-axis string')

    Consider the previous example of plotting the function y=exp(5t-1).

    title('an exponential plot')xlabel('time (sec)')ylabel('the function values, specified units')The plot appears as shown

    Dr. R.N. Patel, email: [email protected] 117

    any other text can be put at any location inside the plot in oneof the two ways:

  • 8/12/2019 MATLAB Short Notes

    118/312

    of the two ways:

    Using the text command: This involves knowing the exact

    coordinates of the point where you want the text string. Thesyntax is:

    text(x_coordinate,y_coordinate,'textstring')

    Using the gtext command: The syntax of this command is:gtext('textstring')

    After issuing this command at the command prompt, you shouldmove the cross-hair to the desired location with the mouse,and click at the position you want the text string to be placed.

    Dr. R.N. Patel, email: [email protected] 118

    Following is the complete m-file to summarize what you learntso far about the plot aesthetics:

  • 8/12/2019 MATLAB Short Notes

    119/312

    so a about t e p ot aest et cs:---------------------------add_text.m-----------------------------% Learning Plot Aesthetics T=0:0.01:5; take the time range of 0 to 5 sec.Y=exp(5*T)-1;

    y is a function of time tplot(T,Y) plots y for given time rangeaxis([0, 1, 0, 50]) set the axes limits for better claritytitle('an exponential plot') this gives a title to your plotxlabel('time (sec)') label for x-axis (must be a st ring .)ylabel('the function values, specified units') label for y-axisgtext('labeling at any location') put a label anywhere

    within the plot

    -----------------------------------------------------------------------------------------Execute the above m-file at your MATLAB window by setting proper path and

    typing the following command:

    >> add_text Dr. R.N. Patel, email: [email protected] 119

    Multiple Plots

  • 8/12/2019 MATLAB Short Notes

    120/312

    Many times you may have to plot many functions in differentfigures or multiple functions in the same figure. For example,

    an electrical engineer may be interested to plot the currentdrawn and the power consumed by a device as a function oftime on the same figure. The following piece of code is aninitial attempt to create many plots together:

    >> X = linspace(0,2*pi,50);>> Y = sin(X); % Y is the first function of X>> Z = cos(X); % Z is the second function of X>> W = tan(X); % W is the third function of X

    Let us plot the data Y versus X:>> plot (X,Y)

    Dr. R.N. Patel, email: [email protected] 120

    Next you can plot data Z versus X using the following command:

  • 8/12/2019 MATLAB Short Notes

    121/312

    y p g g>> plot (X,Z)

    If you desire each plot to be displayed in a separate figure window:>> plot (X,Y)>> figure % this command will create a new figure window

    % to be used for your next plot>> plot (X,Z)

    After entering the above code, you will have the plots in two different figurewindows. Each time you issue the figure command, it creates a new figurewindow which can be used for plotting a new dataset. The most recentbecomes the current figure window.

    All the subsequent plot editing commands (such as changing the axes andadding texts) are applicable to this current figure window.

    Dr. R.N. Patel, email: [email protected] 121

    For example the command below labels the figure depicting

  • 8/12/2019 MATLAB Short Notes

    122/312

    For example, the command below labels the figure depictingplot(X,Z):

    >> plot (X,Y)

    >> figure

    >> plot (X,Z)

    >> title(Plot of z=cos(x));>> xlabel(angle x);

    >> ylabel(Z);

    Suppose you want to label or edit plot(X,Y) figure in the above example. Youcan do so by clicking over plot(X,Y) figure with your mouse button. Thismakes the desired window as your current figure window

    Dr. R.N. Patel, email: [email protected] 122

    You can close any window, either by using the mouse button, or by issuing the

  • 8/12/2019 MATLAB Short Notes

    123/312

    following command:

    >> close % This command will close the

    % window, which is

    % acting as the current figure window

    >> close all % closes all the open figure windows

    If you like to just clear the plot and want to use the same figure window for

    another plot then, then the following command is helpful:

    >> clf % clears the plot from the current figure window, while

    % keeps the window open for the next plot

    Dr. R.N. Patel, email: [email protected] 123

    Multiple Plots on a Window

  • 8/12/2019 MATLAB Short Notes

    124/312

    pIn order to plot more than one function on one figure window, there are two

    ways listed below:

    Using single plot command: The first one is to use only one plot commandwith the parameters for all the functions to be plotted.Using multiple plot commands: The second one is to use multiple plot commands but use hold on command to plot all the curves on the samefigure window.

    The following example illustrates the usage of single plot command. Thefollowing M-file can be used to plot a sine wave and a cosine wave on thesame set of axes, using different color and point markers:

    -------------------------mult_plot1.m-----------------------------X = linspace(0,2*pi,50); % Take 50 samples for x in range 0 to 2*piY = sin(X); Z = cos(X);plot(X,Y,'r', X,Z,'bx') % could be more than two plots as well legend ('sin x', 'cos x', 0) % This is for labeling the two curves---------------------------------------------------------------------------------

    Dr. R.N. Patel, email: [email protected] 124

    The legend function used in above code creates the legends for

  • 8/12/2019 MATLAB Short Notes

    125/312

    The legend function used in above code creates the legends for

    the plot. The basic form is:

    legend ( string -1, string -2, , pos)

    Where, string-1, string-2, and so forth are the labels associated

    with the plotted functions, and pos is an integer specifying

    where to place the legend. For example, 0 in the previous

    case indicates automatic "best" placement for the Legends.

    Dr. R.N. Patel, email: [email protected] 125

    You can generate identical plot using multiple plot commands. You also usehold on and hold off commands After the use of a hold on command

  • 8/12/2019 MATLAB Short Notes

    126/312

    hold on and hold off commands. After the use of a hold on command,all subsequent plots will be generated over the same figure window,without erasing the previous plot, until the hold off command isissued.

    -------------------------------------- mult_plot2.m----------------------------------- X = linspace(0,2*pi,50); % Choose 50 samples in range 0 to 2*pi

    Y = sin(X); plot(X,Y,'r') % the figure would be created at this% point with y versus x curve

    Z = cos(X);hold on % holds the figure window so as to plot the

    % subsequent plots on the same set of axes

    plot(X, Z,'bx') % z versus x curve is added to the figure hold off % looses the control over current figure. Any

    % subsequent plot command will create a new figure--------------------------------------------------------------------------------------------

    Dr. R.N. Patel, email: [email protected] 126

    Subplotting

  • 8/12/2019 MATLAB Short Notes

    127/312

    Subplotting

    Sometimes creating a single plot for several functions is not

    practical due to different scales and units of the functions.

    In Science and Engineering applications, often it is desirable

    to visualize many functions together, and subplot commandcan easily serve the purpose in place of having many

    different plots and trying to bring them together. Thefollowing example illustrates the difficulty in plotting two

    dissimilar functions.

    Dr. R.N. Patel, email: [email protected] 127

    The average yearly rainfall and production of rice in a particular

  • 8/12/2019 MATLAB Short Notes

    128/312

    The average yearly rainfall and production of rice in a particular

    state is given by the following table for 7 consecutive years:

    To visualize the trend of rainfall and its effect on production of

    the crop, it is desired to plot the given data over a singlewindow. MATLAB does this is as follows:

    Year 1997 1998 1999 2000 2001 2002 2003Yearly Rainfall(in cms) 64.5 72.1 68.7 67.9 68.3 62.5 67.5

    Rice Production(in million tonnes) 4.47 4.52 4.95 5.12 5.10 4.37 5.13

    Dr. R.N. Patel, email: [email protected] 128

    --------------------------------------- mult_plot3.m ---------------------------------

  • 8/12/2019 MATLAB Short Notes

    129/312

    % m-file for rainfall and rice production datayears = [1997 1998 1999 2000 2001 2002 2003];

    rain = [64.5 72.1 68.7 67.9 68.3 62.5 67.5];crop = [4.47 4.52 4.95 5.12 5.10 4.37 5.13];

    % above three variables take the respective data in vector forms.

    plot(years,rain,'r', years,crop,'bx-.') % plots the given yearly% data for rain and crop yield on the same figure window

    xlabel('Year') % on the x axis is year, while y-axis is common to% both rain and production data; the following% legend differentiates the two curves

    legend('average rainfall (cms)','crop yield (million tonnes)',0)------------------------------------------------------------------------------------------

    Dr. R.N. Patel, email: [email protected] 129

    In situations like above Example, where more than one functions is required

  • 8/12/2019 MATLAB Short Notes

    130/312

    to be plotted on a figure, the subplot command is used. The subplot command allows you to separate the figure into as many plots as desired,and arrange them all in one figure. The general format of this command is:

    subplot(m,n,p)

    splits the figure into a matrix of m rows and n columns, thereby creatingm n subplots on one figure window. The variable p creates a handle forthe current figure/plot window, and hence any subsequent plot editingcommands apply to this. For example, subplot(2,2,1) will split the window

    space in 2 2 partitions and the figure handle is set to the (first row, firstcolumn) partition. Any subsequent plot command will create a plot in thispartition.

    Dr. R.N. Patel, email: [email protected] 130

    The following MATLAB code uses subplot command for the rainfall and riceproduction data given in Example 1:

  • 8/12/2019 MATLAB Short Notes

    131/312

    ------------------------- sub_plot1.m ---------------------------

    years = [1997 1998 1999 2000 2001 2002 2003];rain = [64.5 72.1 68.7 67.9 68.3 62.5 67.5];crop = [4.47 4.52 4.95 5.12 5.10 4.37 5.13];% creating subplots for rainfall and rice production datasubplot (2,1,1) % splits the figure into a 2 1 window,

    % you can access the first partition for plottingplot(years,rain,'r') % plot for the rain dataxlabel('Years') % x-label for the current plotylabel('average rainfall (cms)') % y-label for the current plotsubplot (2,1,2) % now access the second portion of a (2,1) windowplot(years,crop,'bx-.') % plot for the crop dataxlabel('Years') % x-label for the current plotylabel('crop yield (million tonnes)') % y-label for the current plot

    ------------------------------------------------------------------- Dr. R.N. Patel, email: [email protected] 131

    --------------------------- ------ sub_plot2.m ---------------------

  • 8/12/2019 MATLAB Short Notes

    132/312

    X = linspace(0,2*pi,50); Choose 50 samples in range 0 to 2*pi

    Y = sin(X); Z = cos(X); W = tan(X);

    subplot(2,2,1) Sets the axis handle for the next plot command

    plot(X,Y) Plot Y versus X curve at the current axis handle

    subplot(2,2,2) Sets the axis handle for the next plot command

    plot(X,Z) Plot Z versus X curve at the current axis handle

    subplot(2,2,3)

    plot(X,W)

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

    Dr. R.N. Patel, email: [email protected] 132

    The plot is shown in Figure. There are only three plots though 2 2 partitions

  • 8/12/2019 MATLAB Short Notes

    133/312

    of 4 subplots were created. If you do not fill all of the subplots you have

    created, MATLAB leaves those subplots as empty space. You could have

    easily created another plot using the line subplot(2,2,4) command.

    A plot command issued after a subplot command places the new plot inwhichever subplot position was last used, erasing the plot that was

    previously in it. For example, in the m-file above, if a plot command wasissued later in the m-file, it would be plotted in the third position in thesubplot, erasing the tangent plot. To solve this problem, the figure shouldbe cleared (using clf ), or a new figure should be specified (using figure

    command ). If you want to return to a certain subplot (say n) for furtherediting, this could be accomplished by using the command subplot(l,m,n) .

    Dr. R.N. Patel, email: [email protected] 133

    Plot the rainfall and crop production data given in Example 1 usingplotyy command

  • 8/12/2019 MATLAB Short Notes

    134/312

    plotyy command.

    MATLAB code using plotyy :

    ------------------------ yyplot.m ------------------------------------% using plotyy command for the data with distinct rangesyears = [1997 1998 1999 2000 2001 2002 2003];rain = [64.5 72.1 68.7 67.9 68.3 62.5 67.5];crop = [4.47 4.52 4.95 5.12 5.10 4.37 5.13];plotyy(years,rain, years,crop) % chooses left hand y-axis for average% rainfall data and right hand y-axis% for crop yield data

    xlabel('Years') % on common x axis is Yearsgtext('average rainfall (cms)') % to label the first curve

    gtext ('crop yield(million tonnes)') % label for the second curve------------------------------------------------------------------------------------------

    Dr. R.N. Patel, email: [email protected] 134

    S O h U f l 2 D Pl

  • 8/12/2019 MATLAB Short Notes

    135/312

    Some Other Useful 2-D Plots:

    The plot command gives you a linear plot. Linear plots are most

    useful and frequently used, yet there are other important

    plot types such as pie-charts, bar-charts, and logarithmic

    plots. MATLAB provides an easy way to create many such

    plot types. Following are a few examples on some of the

    plot types.

    Dr. R.N. Patel, email: [email protected] 135

    Plotting a pie chart

  • 8/12/2019 MATLAB Short Notes

    136/312

    The rough estimate of a typical households monthly budget is

    given in the table below. Plot a Pie chart for the same andemphasize the second slice in the chart.

    Budget Component Total Expenditure (in Rs.)

    EssentialsLuxuriesEntertainmentChildrens Education Medical Care

    Savings

    5, 0008, 0002, 0005, 0001, 500

    2, 500Grand Total (Rs.) 24, 000

    Dr. R.N. Patel, email: [email protected] 136

    Following M-file plots a pie-chart:

  • 8/12/2019 MATLAB Short Notes

    137/312

    -------------------------------------- pie_chart.m --------------------------%A typical pie-chart

    x = [5000, 8000, 2000, 5000, 1500, 2500]; % vector x% corresponds to the given data set in the problem

    labels = {'Essentials', 'Luxuries', 'Entertainment', 'Childrens ... Education', 'Medical Care', 'Savings'};

    % give labels sequentially to your data within a { }explode = [0 1 0 0 0 0]; % vector explode is set to 1, for the

    % slice that you want to highlight pie (x, explode, labels) % plot the pie chart for the given datatitle ('a typical Households monthly budget')

    % gives a title for the given chart------------------------------------------------------------------------------------------

    Dr. R.N. Patel, email: [email protected] 137

    Drawing a histogram

    Following are the marks obtained by 70 students of a class in a

  • 8/12/2019 MATLAB Short Notes

    138/312

    certain subject with maximum marks equal to 50:

    marks = [32, 45, 7, 38, 40, 15, 5, 26, 0, 11, 40, 2, 18, 8, 31, 4, 27,7, 0, 15, 12, 35, 28, 46, 9, 29, 10, 34, 2, 7, 5, 17, 2, 8, 35, 30,11, 36, 47, 19, 16, 0, 18, 16, 14, 2, 38, 41, 42, 17, 45, 28, 48,

    20, 7, 21, 8, 5, 28, 13, 22, 27, 41, 40, 36, 29, 29, 31, 34, 48]

    Arrange this data to plot the marks as a histogram of 7 bins.Analyze the total number of students falling under differentmarks intervals. Also draw an approximate plot showing howthe frequency of students varies with increasing marks.

    Dr. R.N. Patel, email: [email protected] 138

    Here are the simple commands for the desired plot (assuming that vectork h l d b d i b )

  • 8/12/2019 MATLAB Short Notes

    139/312

    marks have already been entered as given above) :------------------------- histogram.m -------------------------

    hist (marks, 7) % plots the histogram for the given data with 7 bins title('Marks Distribution in Subject ABC')xlabel('Marks Ranges')ylabel('No. of Students')

    hold on % hold the plot to draw the frequency curve[n, x] = hist (marks, 7) % n gives the frequency falling under

    % each bin and x is the vector containing % the location of bin centers.

    plot (x, n, 'md--') % plots a dashed graph on the same plot,

    % showing the frequency curve.hold off-----------------------------------------------------------------------------------------

    Dr. R.N. Patel, email: [email protected] 139

  • 8/12/2019 MATLAB Short Notes

    140/312

    Advanced Concepts on PlotAnnotation and Labeling

    Dr. R.N. Patel, email: [email protected] 140

    Using Handle Graphics:

    Whenever a plot or multiple plots are created MATLAB defines a handle to

  • 8/12/2019 MATLAB Short Notes

    141/312

    Whenever a plot or multiple plots are created, MATLAB defines a handle to

    all the important objects of the plot, such as the axes, the labels, and

    the curve itself. A handle can be thought of as an identity or an

    address of a particular object within a plot. MATLAB assigns an

    address to each object and if you provide that address, MATLAB can

    also retrieve a list of the current properties of that object. You can

    then change any desired property and feature of the object.

    Some of the important MATLAB functions on handles are listed below:

    gca: get handle to current axes

    gcf: get handle to current figure

    gco: get handle to current object

    Dr. R.N. Patel, email: [email protected] 141

    If you want to modify the properties of the axes of the current

  • 8/12/2019 MATLAB Short Notes

    142/312

    plot, you must first get the handle of the axes as shownbelow:

    h1 = gca % the variable name h1 gets the handle of% the axes of the current plot

    The next step is to know the properties of the axes. You canknow the properties of the axes using get command asshown in the code below:

    >> figure % creates a new figure window

    >> h1 = gca % gets the handle to the axes>> get(h1) % get the list of all the properties of

    % the object with handle h1.

    Dr. R.N. Patel, email: [email protected] 142

    Next, you can change any of the enlisted properties such as FontName using setcommand. The format of set command is as follows:

    t(H 'P t N ' P t V l )

  • 8/12/2019 MATLAB Short Notes

    143/312

    set(H,'PropertyName',PropertyValue)

    You can also set multiple property values with a single statement using the

    following format of set command:

    set(H,'PropertyName1',PropertyValue1,'PropertyName2',PropertyValue2,.............)

    The following example illustrates the use of set command:

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

    >> figure>> h1 = gca;

    >> set(h1, 'FontSize',12,'FontWeight','bold')

    >> plot(2:8, 3:9) % this plot will be with the axes properties in

    % previous command>> set(h1, 'FontSize',20,'FontWeight','bold') % changes the axes

    % properties as per the specifications given

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

    Dr. R.N. Patel, email: [email protected] 143

    Example: The process of Carbon dating is that the amount of

  • 8/12/2019 MATLAB Short Notes

    144/312

    time that has passed can be measured with the help of the

    following Radio-active decay equation:Q t = Q 0. e

    - . t

    where, Q t is the amount of radio-active C14 present at present

    time, Q 0 is the initial amount of radio-active C14 and is thedecay constant (0.00012097/year, for C-14).

    Write a program to plot the percent of C-14 remaining as a

    function of time and indicate the half life period in the curve.

    Dr. R.N. Patel, email: [email protected] 144

    Solution:

    The equation can be written as:

  • 8/12/2019 MATLAB Short Notes

    145/312

    t = - 1/ . log e(Q t /Q 0)

    The half life period of C-14 is the time required for the amount of C-14 to becomehalf of the original amount, i.e., Q t = 0.5Q 0.

    The MATLAB code for the given task is written below:

    -------------------------------------- C_dating.m -----------------------------------------------

    % m-file Program for Carbon Dating

    t= 0:100:10000;

    lamda= 0.00012097;

    q_percent= 100*exp(-lamda.*t);

    plot(t, q_percent, 'LineWidth',1)

    set(gca, 'LineWidth',1, 'Fontsize',10)

    xlabel('\bf\fontsize{10} Time elapsed in years')

    ylabel('\bf\fontsize{10} % of C-14 remaining') Dr. R.N. Patel, email: [email protected] 145

    text(3000,100*exp(-lamda*3000),' \leftarrow Q_t/Q_0 = e^{-\lambda.t} ')

  • 8/12/2019 MATLAB Short Notes

    146/312

    ( p( ) )

    hold on

    half_life = -1/lamda*log(0.5)

    plot (half_life, 50,'s','MarkerEdgeColor','k',...

    'MarkerFaceColor',[.49 1 .63],'MarkerSize',8)

    line([0 half_life],[50 50],'LineStyle',':','color','k')

    line([half_life half_life],[10 50],'LineStyle',':','color','k')

    text(100,48,'\it\bf\fontname{courier}\fontsize{10} half life period of C-14')

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

    Dr. R.N. Patel, email: [email protected] 146

    The Plot

  • 8/12/2019 MATLAB Short Notes

    147/312

    0 1000 2000 3000 4000 5000 6000 7000 8000 9000 1000010

    20

    30

    40

    50

    60

    70

    80

    90

    100

    Time elapsed in years

    % o

    f C - 1

    4 r e

    m a i n

    i n g

    Q t /Q 0 = e- .t

    half l ife period of C-14

    Q t /Q 0 = e- .t

    half l ife period of C-14

    Dr. R.N. Patel, email:

    [email protected]

    LaTeX syntax for Upper and Lower case Greek letters and Mathematical Symbols

    Lower case lettersUpper

    case lettersMathematical symbols

  • 8/12/2019 MATLAB Short Notes

    148/312

    Lower case letters case letters

    Symbol Syntax Symbol Syntax Symbol Syntax Symbol Syntax Symbol Syntax

    \alpha \rho \Gamma \int \propto

    \beta \sigma \Delta \sum \circ

    \gamma \tau \Lamda \cong \infty

    \delta \omega \Pi \sim \prime

    \epsilon \kappa \Sigma \neq \leftarrow

    \eta \xi \Omega \geq \Leftarrow

    \theta o \Theta \leq \rightarrow

    \lambda \upsilon \Xi >> \gg \uparrow

    \mu \zeta \Upsilon

  • 8/12/2019 MATLAB Short Notes

    149/312

    There is an easier method to edit the plots in a dynamic wayusing the Graphical User Interface (GUI) available in the Figure

    Window. Take the example of one of the plots that wascreated previously.

    x = linspace(0,2*pi,50);

    y = sin(x); z = cos(x);

    plot(x,y,'r', x,z,'bx')

    legend ('sinx', 'cosx', 0)

    Dr. R.N. Patel, email: [email protected] 149

    3-D Graphics 3 D plots have their own important role in plotting the functions that cannot

  • 8/12/2019 MATLAB Short Notes

    150/312

    3-D plots have their own important role in plotting the functions that cannotbe interpreted well in a 2-D plane. If a certain function z depends on the

    two variables x and y, in order to know the nature of such a functionover x-y plane, you need a 3-Dimensional plot.

    MATLAB has several built-in functions for plotting three-dimensional objects.

    to plot curves in space ( plot3 ),

    mesh surfaces ( mesh ),

    surfaces ( surf ) and

    two functions for plotting special surfaces, sphere and cylinder

    use MATLAB help on 3-D plots ( >> help graph3d ), to find more information oncertain plot features.

    Dr. R.N. Patel, email: [email protected] 150

    Following is an illustration of a 3-D plot:

  • 8/12/2019 MATLAB Short Notes

    151/312

    An object moves over x-y plane with the following functions oftime t:

    x = t*cos(t),

    y = t*sin(t),

    Find the trajectory of the objects movement for the timeinterval

    (-10 < t < 10 ), taking the time along z-axis.

    The m-file for the problem is given below:

    Dr. R.N. Patel, email: [email protected] 151

    ------------------------------------ plot3D1.m ----------------------------

    %trajectory of the object with time t; t is along z-axis

  • 8/12/2019 MATLAB Short Notes

    152/312

    t = -10*pi:pi/100:10*pi;

    x = t.*cos(t); % note that this is an array multiplication; will

    % require a dot operator preceding *

    y = t.*sin(t);

    h = plot3(x,y,t); % plots x, y and t in a 3-D space

    title('Curve u(t) = < t*cos(t), t*sin(t), t >') % curve title

    xlabel('x')

    ylabel('y')

    zlabel('time')

    grid % sets the grid lines to the plot.

    %grid off remove them

    ---------------------------------------------------------------------------------------- Dr. R.N. Patel, email: [email protected] 152

    Now execute the following:

  • 8/12/2019 MATLAB Short Notes

    153/312

    g

    >> sphere(30);

    >> figure

    >> cylinder([1 0])

    >> title('Unit cone')

    Dr. R.N. Patel, email: [email protected] 153

    Function Plotters

  • 8/12/2019 MATLAB Short Notes

    154/312

    fplot(function, LIMS)

    % plots the function FUN between the x-axis

    % limits specified by LIMS = [xmin xmax].% Use of LIMS = [xmin xmax ymin ymax], also controls the y-axis

    % limits. The function must be supplied within the quotes.

    e.g.Let us take the simple exponential equation ( y = e 5t -1 ).

    >> fplot('exp(5*t)-1', [0 1 0 50]) % note that in place of t, it% could be x or y or any other single variable as well.

    Dr. R.N. Patel, email: [email protected] 154

    Suppose, there is function in x and y as:

  • 8/12/2019 MATLAB Short Notes

    155/312

    x2 + y2 - 4*x*y + 1/5 = 0

    If you are asked to plot this expression using fplot , you will have tough time

    in writing it in the form of y = f(x). In order to see that dependency of

    y over x for the range {-3 < x < 3 }, type the following at MATLAB

    prompt:

    >> ezplot('x^2 + y^2 - 4*x*y + 1/5',[-3,3])

    Dr. R.N. Patel, email: [email protected] 155

  • 8/12/2019 MATLAB Short Notes

    156/312

    -1-0.5

    00.5

    1

    -1

    -0.5

    0

    0.5

    10

    0.2

    0.4

    0.6

    0.8

    1

    Thank You !

    Dr. R.N. Patel, email: [email protected] 156

  • 8/12/2019 MATLAB Short Notes

    157/312

    Session-4Control Structures, Loops, and Functions

    Dr. R.N. Patel, email: [email protected] 157

    4.1 Introduction

  • 8/12/2019 MATLAB Short Notes

    158/312

    4.2 Conditional Statements

    4.3 Loops

    4.4 Nested Loops

    4.5 Breaking Control Structures

    (break and continue)

    4.6 Functions

    Dr. R.N. Patel, email: [email protected] 158

    There are two conditional constructs provided by MATLAB: the if constructand the switch construct.

  • 8/12/2019 MATLAB Short Notes

    159/312

    >> marks = 57; % the variable has to be assigned a value before we

    % can use it in an expression;>> if (marks>35)disp('Pass')end % it wont display anything unless you put an end

    % there

    Dr. R.N. Patel, email: [email protected] 159

    Consider another example as follows:

    3 b 2

  • 8/12/2019 MATLAB Short Notes

    160/312

    >> a = 3;b=2;

    >> if (a>b) disp('a is larger'); disp('b is smaller'); end; c=5

    MATLAB respond