A Quick Start on MATLAB

download A Quick Start on MATLAB

of 11

Transcript of A Quick Start on MATLAB

  • 8/14/2019 A Quick Start on MATLAB

    1/11

  • 8/14/2019 A Quick Start on MATLAB

    2/11

    AA =

    1 2 3

    4 5 6

    7 8 9

    Be careful! MATLAB is case-sensitive, so A and a, are different beasts from

    MATLABs point of view!

    Operations on matricesNow that you have introduced a matrix to MATLAB you can do whatever you

    want with it! For example you can transpose it. How?! Very easy just type: A

    ans =

    1 4 7

    2 5 8

    3 6 9

    Or you can find sum of the elements in each column: sum(A)

    ans =

    12 15 18

    Note: ifA is a vector (row vector or column vector), sum(A) returns the sum over all its

    elements.Question: How do you get summation of elements in each row?

    Question: How do you get summation of over all the elements?

    All the following operators work with the same as sum(.):

    mean(A) : Returns average of elements in a vector (row vectorcontaining average of each column, for matrices)

    var(A) : Returns variance of elements in a vector (row vector

    containing variance of each column, for matrices)

    For standard deviation use std(A).

    median(A) : Returns average of elements in a vector (row vector

    containing average of each column, for matrices)

    max(A) : Returns maximum element in a vector (row vector containing

    maximum element in each column, for matrices)

    min(A) : Returns minimum element in a vector (row vector containing

    minimum element in each column, for matrices)

    In many cases you need to know the position of the maximum or minimum element. You

    can use the following command: [m,i]=max(A)

    m =

    7 8 9

    i =

    3 3 3

    Where, m contains the maximum elements of each column, and i contains the position of

    the maximum element in each column.

  • 8/14/2019 A Quick Start on MATLAB

    3/11

    Access to a matrixs elements (Subscripts):Accessing to a elements of a matrix is very easy, for example if you want to show

    the element in 3rd row and 1st column:

    A(3,1)

    ans =

    7

    and if you want to show the whole 3rd column, just use colon: A(:,3)

    ans =

    3

    6

    9

    Some other useful operators on matrices* In order to find dimensions of a matrix, use size: size(A)

    ans =

    3 3

    For vectors, you can also use length.

    *From linear algebra, we know that all the useful information about a matrix is stored in

    its eigenvalues and eigenvectors. Use function eig: eig(A)

    ans =

    16.1168

    -1.1168

    -0.0000

    What appears on screen is a vector containing eigenvalues ofA. In order to get

    eigenvectors use: [V,D]=eig(A)

    V =

    0.2320 0.7858 0.4082

    0.5253 0.0868 -0.8165

    0.8187 -0.6123 0.4082

    D =

    16.1168 0 0

    0 -1.1168 0

    0 0 -0.0000

    V contains eigenvectors ofA and diagonals ofD are eigenvalues.

    *To get diagonal elements of a matrix use:

  • 8/14/2019 A Quick Start on MATLAB

    4/11

    diag(A)

    ans =

    1

    5

    9

    * To find determinant of a matrix, just type1: det(A)

    ans =

    0

    *To find inverse of a matrix, just type2: inv(A)

    Warning: Matrix is close to singular or badly scaled.

    Results may be inaccurate. RCOND = 2.055969e-018.

    ans =

    1.0e+016 *

    -0.4504 0.9007 -0.4504

    0.9007 -1.8014 0.9007

    -0.4504 0.9007 -0.4504

    Special matricesMany times, in your programs you need to have a matrix of zeros, ones, identity

    matrix or random matrices of arbitrary size.

    zeros(m,n) : mn matrix of zero elements

    ones(m,n) : mn matrix of ones

    eye(m,n) : mn matrix with ones on principal diagonal and zero

    elsewhere

    rand(m,n) : mn matrix with uniform(0,1) random elementsrandn(m,n) : mn matrix with normal(0,1) random elements

    For more matrix functions type help elmat on MATLAB command window.

    Matrices as argument of a mathematical functionAll the mathematical functions operate on each element of a matrix. For example

    function log(A), returns logarithm of each of the elements in A: log(A)

    ans =

    0 0.6931 1.09861.3863 1.6094 1.7918

    1 The determinant is not exactly zero, but MATLAB round up the numbers that it shows on the screen. Sovery small numbers appear as zero, be careful! Many of the 0s that you see on the screen might not be

    zero!2 Good! Now you are exposed to MATLABs warnings. They are not errors (they dont stop the flow of

    your computation), but sometimes they are extremely helpful for tracking mistakes in your program.

    Fortunately, MATLAB is very generous in producing them; youre going to see a lot of these warnings if

    you are thinking of being a MATLAB expert!

  • 8/14/2019 A Quick Start on MATLAB

    5/11

    1.9459 2.0794 2.1972

    For more help on mathematical functions type help elfun on MATLAB command

    window.

    Summation, subtraction, multiplication and division

    You can perform all the basic operations, as long as you dont violate thedimensions requirements. MATLAB also lets you perform multiplications and divisions

    element by element. Look at the following example (Look at the dot,.): a=[12 34 5];

    b=[2 17 1];

    a./b

    ans =

    6 2 5

    a.*b

    ans =

    24 578 5

    For square matrices you cab calculate a number to the power of a matrix: 2^A

    ans =

    1.0e+004 *

    0.7962 0.9782 1.1603

    1.8029 2.2154 2.6276

    2.8097 3.4523 4.0950

    You can also perform this, element by element (Look at the dot, .):

    2.^A

    ans =

    2 4 8

    16 32 64

    128 256 512

    For more information on operators type help ops in MATLAB command window.

    Flow ControlMATLAB has five flow control constructs:

    if statements

    switch statements for loops

    while loops

    break statements

    ifThe if statement evaluates a logical expression and executes a group of statements whenthe expression is true. The optional elseif and else keywords provide for the execution of

  • 8/14/2019 A Quick Start on MATLAB

    6/11

  • 8/14/2019 A Quick Start on MATLAB

    7/11

    R =

    12 34 5

    144 1156 25

    1728 39304 125

    Note: The increments in the first line need not be 1, in fact you can have the counter

    counts at any pace, e.g.: for t=-21:.9:12,

    In fact the above command can be used to generate a vector of equally spaced numbers. t=1:.5:4;

    t

    t =

    1.0000 1.5000 2.0000 2.5000 3.0000 3.5000 4.0000

    whileThe while loop repeats a group of statements an indefinite number of times under control

    of a logical condition. A matching end delineates the statements.Here is a complete program, illustrating while, if, else, and end, that uses interval

    bisection to find a zero of a polynomial. a = 0; fa = -Inf;

    b = 3; fb = Inf;

    while b-a > eps*b

    x = (a+b)/2;

    fx = x^3-2*x-5;

    if sign(fx) == sign(fa)

    a = x; fa = fx;

    else

    b = x; fb = fx;

    end

    endx

    The result is a root of the polynomialx3 - 2x - 5, namelyx =

    2.0946

    breakThe break statement lets you exit early from a for or while loop. In nested loops, break

    exits from the innermost loop only.Here is an improvement on the example from the previous section. a = 0; fa = -Inf;

    b = 3; fb = Inf;

    while b-a > eps*b

    x = (a+b)/2;

    fx = x^3-2*x-5;

    if fx == 0

    break

    elseif sign(fx) == sign(fa)

    a = x; fa = fx;

    else

    b = x; fb = fx;

  • 8/14/2019 A Quick Start on MATLAB

    8/11

    end

    end

    x

    x =

    2.0946

    Question: Why is the use of break a good idea?

    GraphsOne of easiest things to do with MATLAB is drawing a graph, It is also where

    you have the most fun with MATLAB! Look at the following example: t=1:.1:50;

    x=exp(-t/10).*sin(t/2);

    plot(t,x)

    And the following graph appears in a new graph window.

    Get more information by typing help plot on command window. Also some other

    useful graphical functions are subplot, hold, grid and hist. Make sure to take a

    look at MATLAB help on these commands, they are very useful.

    Help and Online Documentation4

    There are several different ways to access online information about MATLAB functions.

    The help command

    The help window

    The MATLAB Help Desk

    Online reference pages

    Link to The MathWorks, Inc.

    The help CommandThe help command is the most basic way to determine the syntax and behavior of a

    particular function. Information is displayed directly in the command window. For

    example help fliplr

    Shows

    FLIPLR Flip matrix in left/right direction.

    4 The followings are adapted exactly from MATLAB helpdesk since I do not know whether it is accessible

    on our system or not.

  • 8/14/2019 A Quick Start on MATLAB

    9/11

    FLIPLR(X) returns X with row preserved and columns flipped

    in the left/right direction.

    X = 1 2 3 becomes 3 2 1

    4 5 6 6 5 4

    See also FLIPUD, ROT90, FLIPDIM.

    Note: MATLAB online help entries use uppercase characters for the function andvariable names to make them stand out from the rest of the text. When typing function

    names, however, always use the corresponding lowercase characters because MATLAB

    is case sensitive and all function names are actually in lowercase.All the MATLAB functions are organized into logical groups, and MATLAB's directory

    structure is based on this grouping. For example, all the linear algebra functions reside in

    the matfun directory. To list the names of all the functions in that directory, with a briefdescription of each: help matfun

    Matrix functions - numerical linear algebra.

    Matrix analysis.

    norm - Matrix or vector norm.

    normest - Estimate the matrix 2-norm

    ...

    The commandhelp

    by itself lists all the directories, with a description of the function category eachrepresents:matlab/general

    matlab/ops

    ...

    The Help WindowThe MATLAB help window is available on PCs by selecting the HelpWindow optionunder the Help menu, or by clicking the question mark on the menu bar. It is also

    available on all computers by typinghelpwin

    To use the help window on a particular topic, typehelpwin topic

    The help window gives you access to the same information as the help command, but the

    window interface provides convenient links to other topics.

    The lookfor CommandThe lookfor command allows you to search for functions based on a keyword. It

    searches through the first line of help text, which is known as the H1 line, for eachMATLAB function, and returns the H1 lines containing a specified keyword. Forexample, MATLAB does not have a function named inverse. So the response fromhelp inverse

    isinverse.m not found.

    Butlookfor inverse

  • 8/14/2019 A Quick Start on MATLAB

    10/11

    finds over a dozen matches. Depending on which toolboxes you have installed, you will

    find entries likeINVHILB Inverse Hilbert matrix.

    ACOSH Inverse hyperbolic cosine.

    ERFINV Inverse of the error function.

    INV Matrix inverse.

    PINV Pseudoinverse.IFFT Inverse discrete Fourier transform.

    IFFT2 Two-dimensional inverse discrete Fourier transform.

    ICCEPS Inverse complex cepstrum.

    IDCT Inverse discrete cosine transform.

    Adding -all to the lookfor command, as inlookfor -all

    searches the entire help entry, not just the H1 line.

    The Help DeskThe MATLAB Help Desk provides access to a wide range of help and reference

    information stored on a disk or CD-ROM in your local system. Many of the underlying

    documents use HyperText Markup Language (HTML) and are accessed with an InternetWeb browser such as Netscape or Microsoft Explorer. The Help Desk process can be

    started on PCs by selecting the Help Desk option under the Help menu, or, on all

    computers, by typinghelpdesk

    All of MATLAB's operators and functions have online reference pages in HTML format,

    which you can reach from the Help Desk. These pages provide more details and

    examples than the basic help entries. HTML versions of other documents, including this

    manual, are also available. A search engine, running on your own machine, can query allthe online reference material.

    The doc CommandIf you know the name of a specific function, you can view its reference page directly. Forexample, to get the reference page for the eval function, typedoc eval

    The doc command starts your Web browser, if it is not already running.

    Printing Online Reference PagesVersions of the online reference pages, as well as the rest of the MATLAB

    documentation set, are also available in Portable Document Format (PDF) through theHelp Desk. These pages are processed by Adobe's Acrobat reader. They reproduce the

    look and feel of the printed page, complete with fonts, graphics, formatting, and images.

    This is the best way to get printed copies of reference material.

    Link to the MathWorksIf your computer is connected to the Internet, the Help Desk provides a connection to The

    MathWorks, the home of MATLAB. You can use electronic mail to ask questions, makesuggestions, and report possible bugs. You can also use the Solution Search Engine at

    The MathWorks Web site to query an up-to-date data base of technical support

    information.

  • 8/14/2019 A Quick Start on MATLAB

    11/11

    Learning MoreTo see more MATLAB examples, select Examples and Demos under the menu, or typedemo

    at the MATLAB prompt. From the menu displayed, run the demos that interest you, andfollow the instructions on the screen.

    For a more detailed explanation of any of the topics covered in this book, see

    The MATLAB Installation Guide describes how to install MATLAB on your

    platform.

    Using MATLAB provides in depth material on the MATLAB language, working

    environment, and mathematical topics.

    Using MATLAB Graphics describes how to use MATLAB's graphics andvisualization tools.

    The MATLAB Application Program Interface Guide explains how to write C or

    Fortran programs that interact with MATLAB.

    MATLAB Product Family New Features provides information on what is new in

    this release and information that is useful in making the transition from previous

    releases of MATLAB to this release.For the very latest information about MATLAB and other MathWorks products, point

    your Web browser to:

    http://www.mathworks.comand use your Internet News reader to access the newsgroupcomp.soft-sys.matlab

    Welcome to the world of MATLAB!

    http://www.mathworks.com/http://www.mathworks.com/