Lec1 Matlab Intro

download Lec1 Matlab Intro

of 85

Transcript of Lec1 Matlab Intro

  • 7/29/2019 Lec1 Matlab Intro

    1/85

    Iqra University, Islamabad Campus

    COMM. SYS LAB

    SPRING 2013

  • 7/29/2019 Lec1 Matlab Intro

    2/85

    INTRODUCTION TO MATLABLAB 1

  • 7/29/2019 Lec1 Matlab Intro

    3/85

    What is Matlab ?

  • 7/29/2019 Lec1 Matlab Intro

    4/85

    What is Matlab ?

    *MATLAB is a programming environment for

    algorithm development, data analysis,

    visualization, and numerical computation. Using

    MATLAB, you can solve technical computingproblems faster than with traditional

    programming languages, such as C, C++, and

    Fortran.

    *http://www.mathworks.com/

    http://www.mathworks.com/http://www.mathworks.com/http://www.mathworks.com/
  • 7/29/2019 Lec1 Matlab Intro

    5/85

    What is Matlab? cont.

    A software environment for interactive numerical computations

    Matlab (stands for MATrix LABoratory)

    Applications:

    Communications Systems

    Computational Biology

    Computational Finance

    Control Systems

    Digital Signal Processing

    Embedded Systems

    FPGA Design

    Image and Video Processing Mechatronics

    Technical Computing

    Test and Measurement

    http://www.mathworks.com/communications-systems/?s_cid=ML2012_tab_appshttp://www.mathworks.com/computational-biology/?s_cid=ML2012_tab_appshttp://www.mathworks.com/computational-finance/?s_cid=ML2012_tab_appshttp://www.mathworks.com/control-systems/?s_cid=ML2012_tab_appshttp://www.mathworks.com/dsp/?s_cid=ML2012_tab_appshttp://www.mathworks.com/embedded-systems/?s_cid=ML2012_tab_appshttp://www.mathworks.com/fpga-design/?s_cid=ML2012_tab_appshttp://www.mathworks.com/image-video-processing/?s_cid=ML2012_tab_appshttp://www.mathworks.com/mechatronics/?s_cid=ML2012_tab_appshttp://www.mathworks.com/technical-computing/?s_cid=ML2012_tab_appshttp://www.mathworks.com/test-measurement/?s_cid=ML2012_tab_appshttp://www.mathworks.com/test-measurement/?s_cid=ML2012_tab_appshttp://www.mathworks.com/technical-computing/?s_cid=ML2012_tab_appshttp://www.mathworks.com/mechatronics/?s_cid=ML2012_tab_appshttp://www.mathworks.com/image-video-processing/?s_cid=ML2012_tab_appshttp://www.mathworks.com/fpga-design/?s_cid=ML2012_tab_appshttp://www.mathworks.com/embedded-systems/?s_cid=ML2012_tab_appshttp://www.mathworks.com/dsp/?s_cid=ML2012_tab_appshttp://www.mathworks.com/control-systems/?s_cid=ML2012_tab_appshttp://www.mathworks.com/computational-finance/?s_cid=ML2012_tab_appshttp://www.mathworks.com/computational-biology/?s_cid=ML2012_tab_appshttp://www.mathworks.com/communications-systems/?s_cid=ML2012_tab_apps
  • 7/29/2019 Lec1 Matlab Intro

    6/85

    Strengths of MATLAB

    MATLAB is relatively easy to learn

    Help is too extensive

    Greatbuilt-in functions support

    Numerous toolboxes, blocksets and Simulink formodeling real world engineering problems

    MATLAB code is optimized to be relatively quickwhen performing matrix operations

    MATLAB may behave like a calculator or as a

    programming language MATLAB is interpreted, errors are easier to fix

    State of the artGraphical User Interface

  • 7/29/2019 Lec1 Matlab Intro

    7/85

    Matlab Interface

  • 7/29/2019 Lec1 Matlab Intro

    8/85

    Command Window

    Use the Command Window to enter

    variables and run functions and M-files.

  • 7/29/2019 Lec1 Matlab Intro

    9/85

    Command History

    Statements you enter in the Command Window are logged

    in the Command History.

    In the Command History, you can view previously runstatements, and copy and execute selected statements.

  • 7/29/2019 Lec1 Matlab Intro

    10/85

    Workspace Browser

    The MATLAB workspace consists of the

    set of variables (named arrays) built up

    during a MATLAB session and stored in

    memory.

  • 7/29/2019 Lec1 Matlab Intro

    11/85

    Array Editor

  • 7/29/2019 Lec1 Matlab Intro

    12/85

    Matlab: Variable Names

    Variable names ARE case sensitive

    Variable names can contain up to 63 characters

    Variable names must start with a letter followed

    by letters, digits, and underscores.

    Blanks are NOT allowed in a variable name,

    however _ is allowed.

  • 7/29/2019 Lec1 Matlab Intro

    13/85

    MATLAB special variables

    ans Default variable name for results

    pi Value of inf Infinity

    NaN Not a number e.g. 0/0 i and j i = j = imaginary number

    eps Smallest incremental number

    realmin The smallest usable positive realnumber

    realmax The largest usable positive realnumber

  • 7/29/2019 Lec1 Matlab Intro

    14/85

    Examples:

    >> a=2

    a =

    2

    >> 2*pi

    ans =

    6.2832

  • 7/29/2019 Lec1 Matlab Intro

    15/85

    Types of Variables

    Type Examples Integer 1362,-5656 Real 12.33,-56.3 Complex X=12.23.2i -- (i = sqrt(-1))

    Complex numbers in MATLAB are represented inrectangular form.

    To separate real & imaginary partH = real(X) K= imag(X)

    Conversion between polar & rectangular C1= 1-2i

    Magnitude: mag_c1 = abs(C1)

    Angle: angle_c1 = angle(C1) Note that angle is in radians

  • 7/29/2019 Lec1 Matlab Intro

    16/85

    Other MATLAB symbols

    , separate statements and data

    % start comment which ends at end of line

    ShortcutCtrl+R, Ctrl+T

    ; (1) suppress output

    (2) used as a row separator in a matrix

    : specify range

  • 7/29/2019 Lec1 Matlab Intro

    17/85

    Arithmetic Operators

    Operator Description

    + Addition

    - Subtraction

    .* Multiplication (element wise)

    ./ Right division (element wise)

    .\ Left division (element wise)

    + Unary plus

    - Unary minus

    : Colon operator

    .^ Power (element wise)' Transpose

    * Matrix multiplication

    / Matrix right division

    \ Matrix left division

    ^ Matrix power

  • 7/29/2019 Lec1 Matlab Intro

    18/85

    Relational & Logical Operators

    Operator Description

    & Returns 1 for every element location that is true(nonzero) in both arrays, and 0 for all other elements.

    | Returns 1 for every element location that is true

    (nonzero) in either one or the other, or both, arrays and0 for all other elements.

    ~ Complements each element of input array, A.

    = Greater than or equal to

    == Equal to

    ~= Not equal to

  • 7/29/2019 Lec1 Matlab Intro

    19/85

    Matrices

    MATLAB treats all variables as matrices. For our

    purposes a matrix can be thought of as an array, in

    fact, that is how it is stored.

    Vectors are special forms of matrices and contain only

    one row OR one column.

    Scalars are matrices with only one row AND onecolumn

  • 7/29/2019 Lec1 Matlab Intro

    20/85

    MATLAB Matrices

    A matrix can be created in MATLAB asfollows (note the commas AND semicolons):

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

    matrix =

    1 2 3

    4 5 6

    7 8 9

  • 7/29/2019 Lec1 Matlab Intro

    21/85

    Row Vector:

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

    rowvec = [12 , 14 , 63]

    rowvec =

    12 14 63

    Row vector can also defined in a following way:

    rowvec = 2 : 2 : 10;

    rowvec =

    2 4 6 8 10

  • 7/29/2019 Lec1 Matlab Intro

    22/85

    Column Vector:

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

    colvec = [13 ; 45 ; -2]

    colvec =

    13

    45

    -2

  • 7/29/2019 Lec1 Matlab Intro

    23/85

    Extracting a Sub-Matrix

    A portion of a matrix can be extracted andstored in a smaller matrix by specifying thenames of both matrices and the rows and

    columns to extract. The syntax is:

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

    where r1 and r2 specify the beginning andending rows and c1 and c2 specify thebeginning and ending columns to beextracted to make the new matrix.

  • 7/29/2019 Lec1 Matlab Intro

    24/85

    Extracting a Sub-Matrix

    A row vector can be extracted from amatrix. As an example we create amatrix below:

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

    matrix =

    1 2 3

    4 5 6

    7 8 9

    Here we extract row 2 of the matrixand make a row vector. Note that the2:2 specifies the second row and the1:3 specifies which columns of the row.

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

    rowvec =

    4 5 6

  • 7/29/2019 Lec1 Matlab Intro

    25/85

    Concatenation

    New matrices may be formed out of old ones

    Suppose we have:

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

    b = a(1:2 , 1:2); b = ??

    c = a(1 , :); c = ?? d = a(2:3 , :); d = ??

    e = a[d ;d]; e = ??

  • 7/29/2019 Lec1 Matlab Intro

    26/85

    Concatenation

    Input Output

    [a, a, a] ans = 1 2 1 2 1 23 4 3 4 3 4

    [a; a; a] ans = 1 23 41 23 41 23 4

    [a, zeros(2); zeros(2), a'] ans = 1 2 0 03 4 0 00 0 1 30 0 2 4

  • 7/29/2019 Lec1 Matlab Intro

    27/85

    Useful MATLAB Commands

    clear Clear all variables from work space

    clear x y Clear variables x and y from work space

    clc Clear the command window

    who List known variables whos List known variables plus their size

    lookfor look up whole matlab directory foravailable functions

    doc open the html based help window

    tic toc measure the simulation time ofprogram

  • 7/29/2019 Lec1 Matlab Intro

    28/85

    Scalar Matrix Addition & Subtraction

    a=3;

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

    b =

    1 2 3 4 5 6

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

    c =

    4 5 6

    7 8 9

  • 7/29/2019 Lec1 Matlab Intro

    29/85

    Scalar - Matrix Multiplication

    a=3;

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

    b =

    1 2 3

    4 5 6

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

    c = 3 6 9

    12 15 18

  • 7/29/2019 Lec1 Matlab Intro

    30/85

    Other matrices ops:Determinant & Inverse

    Let a=[1 4 3;4 2 6 ;7 8 9]

    det(a)

    48

    inv(a)

    ans =

    -0.6250 -0.2500 0.3750 0.1250 -0.2500 0.1250

    0.3750 0.4167 -0.2917

  • 7/29/2019 Lec1 Matlab Intro

    31/85

    Other matrices Operations cont.

    a (Find the transpose of matrix)

    ans =

    1 4 7

    4 2 83 6 9

    min(a) :Return a row vector containing theminimum element from each column.

    ans =1 2 3

    min(min(a)): Return the smallest element inmatrix

  • 7/29/2019 Lec1 Matlab Intro

    32/85

    Other matrices Operations cont.

    max(a): Return a row vector containing themaximum element from each column.

    ans =7 8 9

    max(max(a)): Return the max element from

    matrix:ans = 9

    a.^2 :Bitwise calculate the square of eachelement of matrix:

    ans =

    1 16 9

    16 4 36

    49 64 81

  • 7/29/2019 Lec1 Matlab Intro

    33/85

    Other matrices Operations cont.

    sum (a): treats the columns of a as vectors,returning a row vector of the sums of each

    column. ans =

    12 14 18

    sum(sum(a)): Calculate the sum of all the

    elements in the matrix.ans =

    44

  • 7/29/2019 Lec1 Matlab Intro

    34/85

    Example

    Let a=[1 2 3] ; b=[4 5 6];

    a.*b :Bitwise multiply the each element of vector

    a and b:

    ans =

    4 10 18

  • 7/29/2019 Lec1 Matlab Intro

    35/85

    Matrix Division

    MATLAB has several options for matrix division.You can right divide and left divide.

    Right Division: use the slash character A / B

    This is equivalent to the MATLAB expression

    A*inv (B)

    Left Division: use the backslash character

    A \ B

    This is equivalent to the MATLAB expression

    inv (A)*B

  • 7/29/2019 Lec1 Matlab Intro

    36/85

    Common Matrices and Vectors

    Matrix of Zeros - zeros

    Matrix of Ones - ones

    Identity Matrix eye

    Magic Matrix - magic

  • 7/29/2019 Lec1 Matlab Intro

    37/85

    zeros Matrix

    Syntax : zeros array

    Format : zeros(N), zeros(M,N)

    Description:

    This function is used to produce an array ofzeros, defined by the arguments.

    (N) is an N-by-N matrix of array.(M,N) is an M-by-N matrix of array.

    Example;>> zeros(2) >> zeros(1,2)ans = ans =

    0 0 0 00 0

  • 7/29/2019 Lec1 Matlab Intro

    38/85

    Ones Matrix

    Syntax : ones array Format : ones(N), ones(M,N) Description:

    This function is used to produce anarray of ones, defined by the arguments. (N) is an N-by-N matrix of array. (M,N) is an M-by-N matrix of array. Example; >> ones(2) >> ones(1,2) ans = ans = 1 1 1 1 1 1

  • 7/29/2019 Lec1 Matlab Intro

    39/85

    Eye Matrix

    Syntax : identity matrix

    Format : eye (N), eye (M,N)

    Description: Create an NxN or MxN identity matrix (i.e., 1s on the

    diagonal elements with all others equal to zero). (Usually the identitymatrix is represented by the letter I. Type

    Example;

    >> I=eye(3)I =

    1 0 0

    0 1 0

    0 0 1

  • 7/29/2019 Lec1 Matlab Intro

    40/85

    The Help System

    Search for appropriate function

    >> lookfor keyword Rapid help with syntax and function definition >> help function An advanced hyperlinked help system is

    launched by >> helpdesk Complete manuals as PDF files

  • 7/29/2019 Lec1 Matlab Intro

    41/85

    INTRODUCTION TO MATLAB - cont

  • 7/29/2019 Lec1 Matlab Intro

    42/85

    Outline

    Programming environment and search path

    M-files

    Flow Control

    Plotting in Matlab

    Matlab help System

  • 7/29/2019 Lec1 Matlab Intro

    43/85

    Matlab environment

    Matlab construction

    Core functionality as compiled C-code, m-files

    Additional functionality in toolboxes (m-files)

    Today: Matlab programming (construct own m-files)

    Core m-filesC-kernel

    Sig. Proc Contr. Syst.

    User defined

  • 7/29/2019 Lec1 Matlab Intro

    44/85

    The programming environment

    The working directory is controlled by >> dir >> cd catalogue >> pwd The path variable defines where matlab

    searches for m-files >> path >> addpath

  • 7/29/2019 Lec1 Matlab Intro

    45/85

    The programming environment

    Matlab cant tell if identifier is variable or function

    >> z=theta; Matlab searches for identifier in the following order

    1. variable in current workspace

    2. built-in variable

    3. built-in m-file

    4. m-file in current directory

    5. m-file on search path

    Note: m-files can be located in current directory, orin path

  • 7/29/2019 Lec1 Matlab Intro

    46/85

    M-files

    MATLAB can execute a sequence of MATLAB statements

    stored on disk. Such files are called "M-files"

    they must have the file type of ".m"

    There are two types of M-files: Script files

    Function files.

  • 7/29/2019 Lec1 Matlab Intro

    47/85

    M-files

    To make the m-file click on File next select New and click on M-File from

    the pull-down menu as shown in fig

  • 7/29/2019 Lec1 Matlab Intro

    48/85

    M-files

    Here you will type your code, can make changes, etc.

    Save the file with .m extension

  • 7/29/2019 Lec1 Matlab Intro

    49/85

    Types of M-files

    Script Files

    Function Files

    M-files

  • 7/29/2019 Lec1 Matlab Intro

    50/85

    Script files

    Script-files contain a sequence of Matlab

    commands%FACTSCRIPT Compute n-factorial, n!=1*2*...*n

    y = prod(1:n);

    factscript.m

    Executed by typing its name

    >> factscript

    Operates on variables in global workspace

    Variable n must exist in workspace

    Variable y is created (or over-written)

    Use comment lines (starting with %) to document file!

  • 7/29/2019 Lec1 Matlab Intro

    51/85

    Functions

    Functions describe subprogramsTake inputs, generate outputs

    Have local variables (invisible in global workspace)

    function [output_arguments]= function_name(input_arguments) % Comment lines

    function [z]=factfun(n)% FACTFUN Compute factorial% Z=FACTFUN(N)z = prod(1:n);

    factfun.m>> y=factfun(10);

    Functions

  • 7/29/2019 Lec1 Matlab Intro

    52/85

    Functions

    NOTE:

    The function_name must also be the same as the file name (without the ``.m'') in which the

    function

    is stored

  • 7/29/2019 Lec1 Matlab Intro

    53/85

    function y = mean (x)% MEAN Average or mean value.

    % For vectors, MEAN(x) returns the mean value.% For matrices, MEAN(x) is a row vector% containing the mean value of each column.[m,n] = size(x);if m == 1

    m = n;end

    y = sum(x)/m;

    Output Arguments Input ArgumentsFunction Name

    Comments

    Function Code

    Example

  • 7/29/2019 Lec1 Matlab Intro

    54/85

    Flow Control

  • 7/29/2019 Lec1 Matlab Intro

    55/85

    Flow control - selection

    The if-elseif-else construction

    if elseif elseend

    if height>170disp(tall)

    elseif height

  • 7/29/2019 Lec1 Matlab Intro

    56/85

    Logical expressions

    Relational operators (compare arrays of same sizes)

    == (equal to) ~= (not equal)< (less than) (greater than) >= (greater than or equal to)

    Logical operators (combinations of relational operators) & (and)

    | (or)~ (not)

    Logical functions

    xorisemptyanyall

    if (x>=0) & (x

  • 7/29/2019 Lec1 Matlab Intro

    57/85

    Flow control - selection

    The switch construction

    Switch

    case ,

    otherwise< condition >,

    < statement>

    end

    method = 'Bilinear';

    switch (method)

    case {'linear','bilinear'}

    disp('Method is linear')

    case 'cubic'

    disp('Method is cubic')

    case 'nearest'

    disp('Method is nearest')

    otherwise

    disp('Unknown method.')end

  • 7/29/2019 Lec1 Matlab Intro

    58/85

    Flow control - repetition

    Repeats a code segment a fixed number of

    timesfor index=endThe are executed repeatedly.At each iteration, the variable index is assigneda new value from .

    for k=1:12kfac=prod(1:k);disp([num2str(k), ,num2str(kfac)])

    end

  • 7/29/2019 Lec1 Matlab Intro

    59/85

    Example selection and repetition

    function y=fact(n)% FACT Display factorials of integers 1..n

    if n < 1error(No input argument assigned)

    elseif n < 0error(Input must be non-negative)

    elseif abs(n-round(n)) > epserror(Input must be an integer)

    endfor k=1:n

    kfac=prod(1:k);disp([num2str(k), ,num2str(kfac)])

    y(k)=kfac;

    end;

    fact.m

  • 7/29/2019 Lec1 Matlab Intro

    60/85

    Flow control conditional repetition

    while-loops

    are executed repeatedly as long as the evaluates to true

    while end

    k=1;

    while prod(1:k)~=Inf,k=k+1;

    enddisp([Largest factorial in Matlab:,num2str(k)]);

    d k

  • 7/29/2019 Lec1 Matlab Intro

    61/85

    Programming tips and tricks

    Programming style has huge influence on

    program speed!

    tic;X=-250:0.1:250;for ii=1:length(x)

    if x(ii)>=0,s(ii)=sqrt(x(ii));

    elses(ii)=0;

    end;end;

    toc

    tic

    x=-250:0.1:250;s=sqrt(x);s(x

  • 7/29/2019 Lec1 Matlab Intro

    62/85

    Break Command

    Terminate execution of WHILE or FOR

    loop.

    In nested loops, BREAK exits from the

    innermost loop only.

    BREAK is not defined outside of a FOR

    or WHILE loop.n = 1;

    while prod(1:n) < 700

    n = n + 1;

    if n==5

    break;

    end

    end

  • 7/29/2019 Lec1 Matlab Intro

    63/85

    Plotting in Matlab

  • 7/29/2019 Lec1 Matlab Intro

    64/85

    TWO-DIMENSIONALplot() COMMAND

    where x is a vector (one dimensional array), and y is a vector.Both vectors

    musthave the same number of elements.

    The plot command creates a single curve with the x values on

    the abscissa (horizontal axis) and the y values on the ordinate(vertical axis).

    The curve is made from segments of lines that connect the

    points that are defined by the x and y coordinates of theelements in the two vectors.

    The basic 2-D plot command is:

    plot(x,y)

  • 7/29/2019 Lec1 Matlab Intro

    65/85

    PLOT OF GIVEN DATA

    Given data:

    >> x=[1 2 3 5 7 7.5 8 10];>> y=[2 6.5 7 7 5.5 4 6 8];>> plot(x,y)

    A plot can be created by the commands shown below. This can be done

    in the Command Window, or by writing and then running a script file.

    Once the plot command is executed, the Figure Window opens with the

    following plot.

    x

    y

    1 2 3 5 7 7.5 8

    6.5 7 7 5.5 4 6 8

    10

    2

  • 7/29/2019 Lec1 Matlab Intro

    66/85

    PLOT OF GIVEN DATA

  • 7/29/2019 Lec1 Matlab Intro

    67/85

    LINE SPECIFIERS IN THEplot() COMMAND

    Line specifiers can be added in theplot command to:

    Specify the style of the line.

    Specify the color of the line.

    Specify the type of the markers (if markers are desired).

    plot(x,y,line specifiers)

  • 7/29/2019 Lec1 Matlab Intro

    68/85

    LINE SPECIFIERS IN THEplot() COMMAND

    Line Specifier Line Specifier Marker SpecifierStyle Color Type

    Solid - red r plus sign +

    dotted : green g circle o

    dashed -- blue b asterisk *

    dash-dot -. Cyan c point .

    magenta m square s

    yellow y diamond d

    black k

    plot(x,y,line specifiers)

  • 7/29/2019 Lec1 Matlab Intro

    69/85

    LINE SPECIFIERS IN THEplot() COMMAND

    The specifiers are typed inside theplot() 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.

    EXAMPLES:

    plot(x,y) A solid blue line connects the points with no markers.

    plot(x,y,r) A solid red line connects the points with no markers.

    plot(x,y,--y) A yellow dashed line connects the points.

    plot(x,y,*) The points are marked with * (no line between the

    points.)

    plot(x,y,g:d) A green dotted line connects the points which are

    marked with diamond markers.

  • 7/29/2019 Lec1 Matlab Intro

    70/85

    Year

    Sales (M)

    1988 1989 1990 1991 1992 1993 1994

    127 130 136 145 158 178 211

    PLOT OF GIVEN DATA USING LINE

    SPECIFIERS IN THEplot() COMMAND

    >> year = [1988:1:1994];>> sales = [127, 130, 136, 145, 158, 178, 211];>> plot(year,sales,'--r*')

    Line Specifiers:

    dashed red line and

    asterisk markers.

  • 7/29/2019 Lec1 Matlab Intro

    71/85

    PLOT OF GIVEN DATA USING LINE

    SPECIFIERS IN THEplot() COMMAND

    Dashed red line and

    asterisk markers.

  • 7/29/2019 Lec1 Matlab Intro

    72/85

    Formatting the plots

  • 7/29/2019 Lec1 Matlab Intro

    73/85

    8 10 12 14 16 18 20 22 240

    200

    400

    600

    800

    1000

    1200

    DISTANCE (cm)

    INTENSITY(

    lux)

    Light Intensity as a Function of Distance

    Comparison between theory and experiment.

    Theory

    Experiment

    Plot title

    y axislabel

    x axis

    label

    Text

    EXAMPLE OF A FORMATTED 2-D PLOT

    Data symbol

    Legend

    Tick-mark

    Tick-mark label

  • 7/29/2019 Lec1 Matlab Intro

    74/85

    FORMATTING PLOTS

    A plot can be formatted to have a required appearance.

    With formatting you can:

    Add title to the plot.

    Add labels to axes.

    Change range of the axes.

    Add legend.

    Add text blocks.

    Add grid.

  • 7/29/2019 Lec1 Matlab Intro

    75/85

    FORMATTING COMMANDS

    title(string)Adds the string as a title at the top of the plot.

    xlabel(string)

    Adds the string as a label to the x-axis.

    ylabel(string)

    Adds the string as a label to the y-axis.

    axis([xmin xmax ymin ymax])

    Sets the minimum and maximum limits of the x- and y-axes.

  • 7/29/2019 Lec1 Matlab Intro

    76/85

    FORMATTING COMMANDS

    legend(string1,string2,string3)

    Creates a legend using the strings to label various curves (when

    several curves are in one plot). The location of the legend is specified

    by the mouse.

    text(x,y,string)

    Places the string (text) on the plot at coordinate x,y relative to the plot

    axes.

    Example of a formatted plot

  • 7/29/2019 Lec1 Matlab Intro

    77/85

    Example of a formatted plot

    Syntax:

    Example:

    plot(x1, y1, 'clm1', x2, y2, 'clm2', ...)

    x=[0:0.1:2*pi];

    y=sin(x);

    z=cos(x);

    plot(x,y,x,z)

    title('Sample Plot','fontsize',14);

    xlabel('X values','fontsize',14);ylabel('Y values','fontsize',14);

    legend('Y data','Z data')

    grid on

    colorline marker

    Sample Plot

  • 7/29/2019 Lec1 Matlab Intro

    78/85

    Sample Plot

    Title

    Ylabel

    Xlabel

    Grid

    Legend

    EXAMPLE OF A FORMATTED PLOT

  • 7/29/2019 Lec1 Matlab Intro

    79/85

    EXAMPLE OF A FORMATTED PLOT

    Syntax:

    Example:

    plot(x1, y1, 'clm1', x2, y2, 'clm2', ...)

    x=[0:0.1:2*pi];

    y=sin(x);

    z=cos(x);

    plot(x,y,x,z)

    title('Sample Plot','fontsize',14);

    xlabel('X values','fontsize',14);ylabel('Y values','fontsize',14);

    legend('Y data','Z data')

    grid on

    color line marker

    Displaying Multiple Plots

  • 7/29/2019 Lec1 Matlab Intro

    80/85

    Displaying Multiple Plots

    Two typical ways to display multiple curves in

    MATLAB (other combinations are possible)

    One figure contains one plot that contains multiple

    curves Requires the use of the command hold (see

    MATLAB help)

    One figure contains multiple plots, each plot containing

    one curve Requires the use of the command subplot

    Sample plot [using hold on command]

  • 7/29/2019 Lec1 Matlab Intro

    81/85

    Sample plot [using hold on command]

    x=[0:0.1:2*pi];

    y=sin(x);

    z=cos(x);

    plot(x,y,x,z)

    grid on

    x=[0:0.1:2*pi];

    y=sin(x);

    z=cos(x);

    plot(x,y,b)

    hold onplot(x,z,g)

    hold off

    grid on

    Subplots

  • 7/29/2019 Lec1 Matlab Intro

    82/85

    Subplots

    subplot divides the current figure into rectangular panesthat are numbered rowwise.

    Syntax: subplot(rows,cols,index)

    subplot(2,2,1);

    subplot(2,2,2)

    ...

    subplot(2,2,3)

    ...

    subplot(2,2,4)

    ...

    Example of subplot

  • 7/29/2019 Lec1 Matlab Intro

    83/85

    Example of subplot

    x=[0:0.1:2*pi];y=sin(x);

    z=cos(x);

    subplot(1,2,1);

    plot(x,y)subplot(1,2,2)

    plot(x,z)

    grid on

    Summary

  • 7/29/2019 Lec1 Matlab Intro

    84/85

    Summary

    User-defined functionality in m-files Stored in current directory, or on search path

    Script-files vs. functions Functions have local variables, Scripts operate on global workspace

    Writing m-files Header (function definition), comments, program body Flow control: if...elseif...if, for, while General-purpose functions: use functions as inputs

    Programming style and speed

    Vectorization, memory allocation, profiler Plotting in Matlab

    Plot, subplot

  • 7/29/2019 Lec1 Matlab Intro

    85/85

    THE END