MATH15L Coursewares

download MATH15L Coursewares

of 215

Transcript of MATH15L Coursewares

  • 8/3/2019 MATH15L Coursewares

    1/215

    presents

    in cooperation with

  • 8/3/2019 MATH15L Coursewares

    2/215

  • 8/3/2019 MATH15L Coursewares

    3/215

    Course Code: MATH15L

    Course Title: MATLAB

    Pre-requisite:

    Co-requisite: MATH 15

    Credit: 1 unitEquivalent Course Codes: None

    Faculty:

  • 8/3/2019 MATH15L Coursewares

    4/215

    Course Description

    The course utilizes the capability ofinformation technology to facilitate theunderstanding of basic mathematicalprinciples and operations.

    A mathematical software (MATLAB)will be used to perform algebraicoperations, differentiation, integration,

    matrix operations, graphic manipulationand some basic MATLAB programmingfor simulations and analysis.

  • 8/3/2019 MATH15L Coursewares

    5/215

    Course Objectives and

    Relationship to Program ObjectivesIt is a laboratory course in

    mathematics. Its goals are to give the

    students sufficient understanding ofMATLAB and its application for the

    purpose of developing students skill in

    solving problems and to apply their acquired learning in engineering

    applications.

  • 8/3/2019 MATH15L Coursewares

    6/215

    It prepares students to recognize

    patterns and formulate rules as a firststep to develop students skill for

    independent critical thinking.

    The course aims to develop thestudents zest for knowledge,

    application and appreciation of an

    orderly and logical solution as guided bythe different principles undertaken in the

    course.

  • 8/3/2019 MATH15L Coursewares

    7/215

    Course Coverage

    Foundation and FundamentalConcepts

    Arrays and Matrices

    Symbolic MathGraphs

    Programming

  • 8/3/2019 MATH15L Coursewares

    8/215

    Course Outcomes and Relationship

    to Program Outcomes:

    A student completing this course shouldat a minimum be able to:

    perform polynomial operations such asmultiplication and division.

    decompose rational polynomials into sum ofpartial fractions.

    perform the four fundamental operations onmatrices as well as getting the determinant ofsquare matrix.

  • 8/3/2019 MATH15L Coursewares

    9/215

    solve systems of equations and polynomialequations.

    perform differentiation and integration.

    plot the graphs of lines, circles, ellipses,parabolas and hyperbolas.

    plot the graphs of polynomial functions and

    transcendental functions.

    compile a simple MATLAB program.

  • 8/3/2019 MATH15L Coursewares

    10/215

    Course Evaluation

    Points

    Long Tests 2 250 25%

    Classroom Exercise/Hands on

    Exam

    5 450 45%

    Classroom Participation

    Portfolio 1 50 5%

    Final Examination 1 250 25%

    TOTAL 1000 100%

  • 8/3/2019 MATH15L Coursewares

    11/215

    Long Test/Classroom Exercise/

    Hands on Exam/Final Exam

    Guidelines

    No borrowing of terminal/ terminal account.

    Use black ballpen/tech-pen.

    Show your answers clearly.

    Use short white/bond paper.

    Avoid going out during examination.

    No special exam.

  • 8/3/2019 MATH15L Coursewares

    12/215

    Portfolio Guidelines

    No late Portfolio will be accepted.

    Use short black Clear Book.

  • 8/3/2019 MATH15L Coursewares

    13/215

    Average Grade Average Grade

    Below 70 5.00 83.21-86.5 2.00

    70-73.3 3.00 86.51-89.8 1.75

    73.31-76.6 2.75 89.81-93.1 1.50

    76.61-79.9 2.50 93.11-96.4 1.2579.91-83.2 2.25 96.41-100 1.00

  • 8/3/2019 MATH15L Coursewares

    14/215

    Other course Policies

    According to CHED policy, total number of

    absences by the students should not be more

    than 20% of the total number of meetings or

    9 hrs for this one-unit-course. Student

    incurring more than 9 hours of absences

    automatically gets a failing grade regardlessof class standing.

    Attendance

  • 8/3/2019 MATH15L Coursewares

    15/215

    Honor, Dress and Grooming Codes

    All of us have been instructed on the

    Dress and Grooming Codes of the Institute.

    We have all committed to obey and sustainthese codes. It will be expected in this class

    that each of us will honor the commitments

    that we have made.

  • 8/3/2019 MATH15L Coursewares

    16/215

    For this course the HonorCode is that

    there will be no plagiarizing on written work

    and no cheating on exams. If a student is

    caught on two exams, the student will be

    referred to the Prefect of Student Affairs and

    given a failing grade.

  • 8/3/2019 MATH15L Coursewares

    17/215

    Consultation Schedule

    Consultation schedules with the Professor

    are posted outside the Mathematics Faculty

    Room. It is recommended that the student

    first set an appointment to confirm the

    instructors availability if outside the

    consultation schedules.

  • 8/3/2019 MATH15L Coursewares

    18/215

    Computer Laboratory Guidelines

    No student shall be allowed to enter thelaboratory without his or her Instructor.

    EATING, DRINKING, LITTERING and

    VANDALISM in any form are strictly

    prohibited.

    All belongings shall place in the designated

    areas. Valuables and important belongings

    should be brought in.The assigned personnel is not liable for any

    loses or damages that would occur.

  • 8/3/2019 MATH15L Coursewares

    19/215

    A strict one (1) computer to one (1) studentratio shall be observed.

    Students are not allowed to use externaldevices without the approval of the DeputyDirector for Systems Administration.

    Students must notify the assign personnel in

    charge regarding any errors and/orbreakages of facilities and/or equipment intheir designated areas.

    No excessive noise.

    Using mobile phone or any musicalinstrument is strictly prohibited.

    Diskettes are not allowed.

    Accessing the internet is prohibited.

  • 8/3/2019 MATH15L Coursewares

    20/215

    MATLAB BASICS

  • 8/3/2019 MATH15L Coursewares

    21/215

    What is MATLAB?

    - The name stands for MATrix LABoratory

    - MATLAB is a high-performance language for technicalcomputing. It integrates computation, visualization, and

    programmingenvironment.- MATLAB is a modern programming language

    environment: it has sophisticated data structures,contains built-in editing and debugging tools, andsupports object-oriented programming.

  • 8/3/2019 MATH15L Coursewares

    22/215

    THE MATLAB SYSTEM

    - Development Environment

    - The MATLAB Mathematical Function Library

    - The MATLAB Language

    - The MATLAB Application Program Interface (API)

  • 8/3/2019 MATH15L Coursewares

    23/215

    Development Environment

    - Set of tools and facilities that help use MATLABfunctions and files.

    - Includes:

    - MATLAB Desktop- Command Window

    - Command History

    - Editor and Debugger and browsers for viewing help

    - Workspace

  • 8/3/2019 MATH15L Coursewares

    24/215

    MATLAB MATHEMATICAL FUNCTION LIBRARY

    - This is a vast collection of computational algorithmsranging from elementary functions

    Examples:

    > sum, sine, cosine, and complex arithmetic

    > sophisticated functions like matrix inverse, matrixeigenvalues, Bessel functions, and fast Fouriertransforms.

  • 8/3/2019 MATH15L Coursewares

    25/215

    MATLAB LANGUAGE

    - This is a high-level matrix/array language with controlflow statements, functions, data structures,input/output, and object-oriented programmingfeatures.

    - It allows both "programming in the small" to rapidlycreate quick and dirty throw-away programs, and"programming in the large" to create complete largeand complex application programs.

  • 8/3/2019 MATH15L Coursewares

    26/215

    GRAPHICS

    - MATLAB has extensive facilities for displaying vectorsand matrices as graphs, as well as annotating andprinting these graphs.

    - It includes high-level functions for two-dimensional andthree-dimensional data visualization, image processing,animation, and presentation graphics.

    - It also includes low-level functions.

  • 8/3/2019 MATH15L Coursewares

    27/215

    MATLAB APPLICATION PROGRAM INTERFACE

    - This is a library that allows you to write C and Fortranprograms that interact with MATLAB.

    - It includes facilities for calling routines from MATLAB(dynamic linking), calling MATLAB as a computationalengine, and for reading and writing MAT-files.

  • 8/3/2019 MATH15L Coursewares

    28/215

    Development Environment

    Desktop Tools

    - Command Window

    - Command History

    - Star Button and Launch Pad

    - Help Browser

    - Current Directory Browser

    - Workspace Browser- Array Editor

    - Editor/Debugger

    - Profiler

  • 8/3/2019 MATH15L Coursewares

    29/215

  • 8/3/2019 MATH15L Coursewares

    30/215

    WORKSPACE BROWSER

    - Consists of the set of variables during a MATLAB sessionand stored in memory

  • 8/3/2019 MATH15L Coursewares

    31/215

    ARRAY EDITOR

    - Use to edit the variables in the workspace.

    - Three ways to open: double click the variable in theworkspace browser, select the variable in the workspaceand click open , use the openvar syntax

  • 8/3/2019 MATH15L Coursewares

    32/215

    EDITOR/DEBUGGER

    - Used to create and debug M-files, which are programyou write to run the MATLAB functions

  • 8/3/2019 MATH15L Coursewares

    33/215

    Foundation and FundamentalConcepts

  • 8/3/2019 MATH15L Coursewares

    34/215

    Entering Commands and

    Expressions

    The prompt >> is displayed in the Command

    Window and when the Command Window is

    active, a blinking cursor should appear to theright of the prompt.

    This cursor and the MATLAB prompt signify

    that MATLAB is waiting to perform amathematical operation.

  • 8/3/2019 MATH15L Coursewares

    35/215

    clear- Removes all the variables from theworkspace.

    - Frees up system memory

    who- Displays the list of variables currently in

    the memory.

    whos- Will display more details which include

    size, space, allocation and class of variables

    exist - Checks for existence of the variable.

    global - Declares variable to be global.

    help - Searches for help topic

    lookfor - Searches help entries for keyword

    quit - Stops the MATLAB

    Commands for Managing a Session

  • 8/3/2019 MATH15L Coursewares

    36/215

    Help Features in MATLAB

    helpbrowser Opens the help window

    help function_nameDisplays the help document in the

    command window

    helpwin function_nameDisplays the help document in

    separate window

    doc function_name Displays detailed help document in

    separate window

  • 8/3/2019 MATH15L Coursewares

    37/215

    Numeric Display Formats

    format- Controls the display output of the

    command window

    Common Format Functionsshort - Four decimal digits

    long - Sixteen decimal digits

    short e - Five decimal digits plus exponent

    long e - Sixteen digits plus exponent

    bank - Two decimal digits

  • 8/3/2019 MATH15L Coursewares

    38/215

    Mathematical Functions

    ans - Most recent answeri , j - The imaginary unit

    Inf - Infinity

    NaN - Undefined numerical result (not a number)

    pi - The number

    Special Variables and Constants

  • 8/3/2019 MATH15L Coursewares

    39/215

    Mathematical FunctionsElementary Functions

    cos(x) Cosine abs(x) Absolute value

    sin(x) Sine ceil(x) Round towards + Inf

    tan(x) Tangent floor(x) Round towards - Inf

    acos(x) Arc cosine round(x) Roundasin(x) Arc sine rem(x) Remainder after division

    atan(x) Arc tangent angle(x) Phase

    exp(x) Exponential conj(x) Complex Conjugate

    sqrt(x) Square root imag (x) imaginary

    log(x)Natural

    Logarithmreal (x) Real number

    log10(x)Common

    Logarithmprimes (x) Prime Number

  • 8/3/2019 MATH15L Coursewares

    40/215

    Mathematical Functions

    Scalar Arithmetic

    Symbol Operation

    + Addition

    - Subtraction

    * Multiplication

    / Right Division

    \ Left Division

    ^ Exponentiation

  • 8/3/2019 MATH15L Coursewares

    41/215

    Mathematical Functions

    Exponential and Logarithmic Functions

    exponential exp (x)

    Natural Logarithm ln (x)

    Common Logarithm log10 (x) = [ log10 (x) ]

    Square root sqrt (x)

  • 8/3/2019 MATH15L Coursewares

    42/215

    Example1:

    2 + 3 4

    In Command Window>>2 + 3 4

    ans =

    1Example2:

    In Command Window

    >> 6 / 3

    ans =

    2

    36 z

  • 8/3/2019 MATH15L Coursewares

    43/215

    Example3:

    In Command Window

    >> 6 \ 3

    ans =0.5

    MATLAB has assigned the answer to a

    variable called ans, which is an abbreviationfor answer. A variable in MATLAB is asymbol used to contain a value.

    63 z

  • 8/3/2019 MATH15L Coursewares

    44/215

    MATLAB does not care about spaces for themost part. Spaces in the line improve itsreadability.

    When you want to calculate a more complexexpression use parentheses, in the usualway, to indicate precedence.

    The mathematical operations represented bythe symbols + * / \, and ^ follow a set of rules called precedence..

  • 8/3/2019 MATH15L Coursewares

    45/215

    Mathematical expressions are evaluatedstarting from the left, with the exponentiationoperation having the highest order of precedence, followed by multiplication anddivision with equal precedence, followed byaddition and subtraction with equal

    precedence.

    Parentheses can be used to alter this order.Evaluation begins with the innermost pair of

    parentheses, and proceeds outward.

  • 8/3/2019 MATH15L Coursewares

    46/215

    To avoid mistakes, you should feel free to

    insert parentheses wherever you are unsureof the effect precedence will have on the

    calculation.

    Example4:

    In Command Window

    >> (3*(23 + 14.7 (4 / 6))) / 3.5

    5.3

    )6

    47.1423(3

  • 8/3/2019 MATH15L Coursewares

    47/215

    Naming constants and variables

    MATLAB allows us to give constants and

    variables names of our choice. This is a

    powerful facility that can reduce work and

    help in avoiding input errors.

    When the user begins a session in which the

    same values must be used several times, theuser can define them once and then call them

    by name.

  • 8/3/2019 MATH15L Coursewares

    48/215

    Example5:

    Given:

    a = 2, A = 3

    Find:

    a. 2a

    b. w=3A

    In Command Window

    >>a=2

    a =2

    >>A=3;

  • 8/3/2019 MATH15L Coursewares

    49/215

    When you write the semicolon ; at the endof a statement, the computer will not displaythe result of the command, and it will notecho the input.

    >>2*a

    ans =

    4>>w=3*A

    w =

    9

    MATLAB does not tell you the value of all thevariables; it merely gives you their names. Tofind their values, you must enter their names

    at the MATLAB prompt.

  • 8/3/2019 MATH15L Coursewares

    50/215

    >>a = 4

    a =

    4

    >>2*a

    ans =

    8

    If you reuse a variable in the precedingexample, or assign a value to one of the

    special variables, its prior value is overwrittenand lost. However, any other expressionscomputed using the prior value do notchange.

  • 8/3/2019 MATH15L Coursewares

    51/215

    Example6:

    Given:

    E = 30, F = 52, K = 76

    Find:

    a. Sin E

    b. Sin F

    c. Sin K

    In Command Window

    >> alpha = 30;>> beta = 52;

    >> gamma = 76;

  • 8/3/2019 MATH15L Coursewares

    52/215

    >> sin (alpha)

    ans =

    0.9880 A pair of parentheses is used after the

    functions name to enclose the value calledthe functions argument that is operated on

    by the function.>> sin (beta)

    ans =

    0.9866>> sin (gamma)

    ans =

    0.5661

  • 8/3/2019 MATH15L Coursewares

    53/215

    MATLAB remembered past information.

    To recall previous commands, MATLAB uses

    the cursor keys, n, o, p, q, on your

    keyboard.

    In addition, all text after a percent sign (%) is

    taken as a comment statement.

  • 8/3/2019 MATH15L Coursewares

    54/215

    Example ofFormating:

    T or pi

    In Command Window

    >> pi

    ans =

    3.1416

    MATLAB uses high precision for its

    computations, but by default it usually

    displays its results using four decimal places.This is called the short format. Using the

    format command can change this default.

  • 8/3/2019 MATH15L Coursewares

    55/215

    >> format long

    >> pi

    ans =

    3.14159265358979

    MATLAB uses the notation e to represent

    exponentiation to a power of 10.

    >> format short e

    >> pi

    ans =

    3.1416e+000

  • 8/3/2019 MATH15L Coursewares

    56/215

    >> format long e

    >> pi

    ans =3.14159265358979e+000

    >> format bank

    >> pi

    ans =

    3.14

    To return to default format

    >> format

    >> pi

    ans =

    3.1416

  • 8/3/2019 MATH15L Coursewares

    57/215

    Most interesting is the format rat: it yields arational approximation of a real number, thatis a fraction that approximates a givennumber.

    >> format rat

    >>pi

    ans =355/113

    >>format

    >>355/113ans =

    3.1416

  • 8/3/2019 MATH15L Coursewares

    58/215

    Practice Set:

    1. Perform the indicated operation:

    a. 2{ 4 [6 + 3 + (7 (1 + 8)) + 12] 3} + 5

    b. 5{ [ 2 + 6 8(4 (7 4) 2) + 2] 1}

    c.

    d

    e. Given:

    )2(312

    3)2(3

    52

    )4(8

    )2(4

    85

    z

    2

    5x

    T

    !

  • 8/3/2019 MATH15L Coursewares

    59/215

    Determine:

    i. y = sin x

    ii. when y = 1, what is z = sin-1 yg.

    h. cos (T / 2)

    2. Suppose that x = 3 and y = 4. Use MATLABto compute the following.

    a.

    b. 3 T x2

    c.

    3.0cos 1e

    1

    5

    x

    11

    8x4

    y3

  • 8/3/2019 MATH15L Coursewares

    60/215

    d.

    3. Assuming that the variables a, b, c, d and f are scalars, write MATLAB statements to

    compute and display the following

    expressions. Test your statements for the

    values a = 1.12, b = 2.34, c = 0.72, d = 0.81,

    f = 19.83

    a.

    b.

    6x3

    )5y(4

    2f

    c

    b

    a1x !

    cd

    abs

    !

    1 f1 2

  • 8/3/2019 MATH15L Coursewares

    61/215

    c. d.

    4. Evaluate the following expressions inMATLAB, for the values x = 5 + 8i,

    y = 6 + 7i.

    a. u = x + y

    b. v = xy

    c. w = x / y

    d. z = ex

    e.

    f. s = xy2

    d

    1

    c

    1

    b

    1

    a

    1

    1r

    !2

    f

    c

    1aby

    2

    !

    yr!

  • 8/3/2019 MATH15L Coursewares

    62/215

    Polynomial Algebra

    Partial fractionRoots of Equation

    Polynomial and Symbolic Conversion

  • 8/3/2019 MATH15L Coursewares

    63/215

    Command Description

    conv(a, b) Computes the product of thetwo polynomials described by

    the coefficient arrays a and b.

    The two polynomials need not

    be the same degree. Theresult is the coefficient array of

    the product polynomial.

    Consider f(x) = 12x4 3x2 + x + 7. This

    function f can be written in array form calledcoefficient array, that is, f = [12, 0, -3, 1, 7].

  • 8/3/2019 MATH15L Coursewares

    64/215

    Example Answer

    1. (2x+1)(3x-5) 6x^2 -7x -5

    2. (x^2-3)(x^3+2x+1) X^5-x^3+x^2-

    6x-3

  • 8/3/2019 MATH15L Coursewares

    65/215

    [q, r] =

    deconv(num,

    den)

    Computes the result of dividing

    a numerator polynomial,

    whose coefficient array is num,by a denominator polynomial

    represented by the coefficient

    array den.

    Example Answer

    Q= 4x+11

    R= 59x 41

    Q= x+3

    R= 9x -18

    473

    325

    2

    2

    xx

    xx312x

    672

    6

    2

    2

    xx

    xx32x

  • 8/3/2019 MATH15L Coursewares

    66/215

    poly(r) Computes the coefficients of thepolynomial whose roots are specified

    by the vector r. The result is a rowvector that contains the polynomials

    coefficients arranged in descending

    order of power

    Example Answer

    X1=1

    X2=-1

    1 0 -1 => X^2-1

    X1=1

    X2=2

    X3=3

    1 -6 11 -6 => x^3-6x^2+11x-6

  • 8/3/2019 MATH15L Coursewares

    67/215

    [r,p,k] =

    residue(a,b)

    Finds the residues, poles and

    direct term of a partial fraction

    expansion of the ratiopolynomials a(x) / b(x)

    Example Answer

    2

    75

    23

    xxx

    x

    22

    7242

    23

    234

    xxx

    xxxx

    2

    1

    1

    1

    1

    2

    xxx

    2

    1

    1

    1

    1

    22

    xxxx

    l l( ) E l t l i l t

  • 8/3/2019 MATH15L Coursewares

    68/215

    polyval(a, x) Evaluates a polynomial at

    specified values of its

    independent variable x, whichcan be a matrix or a vector.

    The polynomials coefficients of

    descending powers are stored

    in the array a.Example Answer

    1. f(x)=x^2-x+5. Find f(2) 7

    t ( ) C t th t f

  • 8/3/2019 MATH15L Coursewares

    69/215

    roots(a) Computes the roots of a

    polynomial specified by the

    coefficient array a. The resultis a column vector that

    contains the polynomials roots.

    Example Answer

    X^2-1 X1=1

    X2=-1

    x^3-6x^2

    +11x-6

    X1=1

    X2=2

    X3=3

    2 l C t b li l i l

  • 8/3/2019 MATH15L Coursewares

    70/215

    sym2poly Convert a symbolic polynomial

    to polynomial coefficient vector

    Example:

    sym2poly(x^3 - 2*x - 5) returns [1 0 -2 -5]

    poly2sym Convert a polynomial

    coefficient vector to symbolicpolynomial

    Example:poly2sym([1 0 -2 -5]) is x^3-2*x-5

  • 8/3/2019 MATH15L Coursewares

    71/215

    SYMBOLIC PROCESSING

    Process of obtaining answers in the form of

    expressions

    Terms used to describe how MATLAB performs

    operations or evaluates mathematical expressions inthe way, for examples, that humans do algebra with

    pencil and paper.

  • 8/3/2019 MATH15L Coursewares

    72/215

    Symbolic Object

    Symbolic object is a data structure that stores astring representation of the symbol. The two ways tocreate symbolic object are:

    1. Using sym function

    Typing x = sym(x) creates the symbolic

    variable with name x.2. Using syms command

    syms x is equivalent to typing x = sym(x).

    Typing syms x y z creates three symbolic

    variables x, y and z.

    S b li C t t

  • 8/3/2019 MATH15L Coursewares

    73/215

    Symbolic Constants:

    To create symbolic constant, use the sym function.

    >> pi = sym(pi)

    >> fraction = sym(1/4)

    >> sqroot2 = sym(sqrt(2))

    Symbolic Variables & Expressions

    The sequence of commands

    >> syms x y x

    >> m = sqrt (x ^2 + y^2 + z^2)

    >> n = sin (x*y) / (x*y)

    generates the symbolic m and n.

    S b li C t t

  • 8/3/2019 MATH15L Coursewares

    74/215

    Symbolic Constants:

    To create symbolic constant, use the sym function.

    >> pi = sym(pi)

    >> fraction = sym(1/4)

    >> sqroot2 = sym(sqrt(2))

    Symbolic Variables & Expressions

    The sequence of commands

    >> syms x y x

    >> m = sqrt (x ^2 + y^2 + z^2)

    >> n = sin (x*y) / (x*y)

    generates the symbolic m and n.

  • 8/3/2019 MATH15L Coursewares

    75/215

    Symbolic objects can be classified as:

    1. symbolic variable (ex. x, y, z)2. symbolic constant (ex. pi, sqrt(3))

    3. symbolic expression (ex. x^2 + y^2)

    4. symbolic matrix (ex. [a, b, c; b, c, a; c, a, b]

    To create symbolic constant, use the symfunction.

    Example:

    >> pi = sym(pi)>> fraction = sym(1/4)

    >> sqroot2 = sym(sqrt(2))

  • 8/3/2019 MATH15L Coursewares

    76/215

    pretty

    Theprettyfunction displays symbolic output in aformat that resembles typeset mathematics.

    Syntax: pretty (S)

    >>m = sqrt (x^2 + y^2 + z^2)

    m =

    (x^2+y^2+z^2)^(1/2)

    >> pretty (m)

    2 2 2 1/2

    (x + y + z )

  • 8/3/2019 MATH15L Coursewares

    77/215

    Examples:

    >> f = x^3-6*x^2+11*x-6

    >> g= (x-1) * (x-2)* (x-3)

    >> pretty (f)

    >> pretty (g)

    Or

    >> pretty (x^3-6*x^2+11*x-6)

    >> pretty ((x-1) * (x-2)* (x-3))

    double

    The statement double (s) converts the symbolic object Sto a numeric object.

    Syntax: r = double (S)

    >> sqroot2 = sym (sqrt (2));

    >> z = 6* sqroot2

    >> double (z)

    S C O

  • 8/3/2019 MATH15L Coursewares

    78/215

    SIMPLIFICATION:

    Commands

    collect (s) expand (s)

    horner (s) factor (s)

    simplify (s) simple (s)

    ll t

  • 8/3/2019 MATH15L Coursewares

    79/215

    collect

    collect (f) views fas a polynomial in its symbolic

    variables, say x, and collects all the coefficients withthe same power of x.

    Syntax: collect (S)

    Ex.

    1. H =x[x(x-6)+11]-6

    >> h = x * (x *(x-6)+11)-6

    collect (h)

    ans =

    x^3-6*x^2+11*x-6

    Syntax : collect (S, x) the 2nd argument can specifythe variable in which to collect terms if there is morethan one candidate.

    d

  • 8/3/2019 MATH15L Coursewares

    80/215

    expand

    expand (f) distributes products over sums and applies

    other identities involving transcendental functions.

    Syntax: expand (S)

    Ex.

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

    3. e a+b

    h

  • 8/3/2019 MATH15L Coursewares

    81/215

    horner

    horner (f) transforms a sumbolic polynomial finto its

    Horner, (or nested, representation)

    Syntax: horner (f)

    Ex.

    1. (x3

    3x2

    4x +5)2. 2x5 x4 + 3x2 4x +5

    3. 1.1 + 2.2x + 3.3x2

    factor

  • 8/3/2019 MATH15L Coursewares

    82/215

    factor

    factor (S) factors the expression Swhich can be

    positive integer, an array of symbolic expressions, oran array of symbolic integers.

    Syntax: factor (S)

    Ex.

    1. factor (x^3 - y^3)

    simplify

  • 8/3/2019 MATH15L Coursewares

    83/215

    simplify

    simplify (E) simplify the expression E using Maples

    simplification rules.

    Ex.

    >> simplify (sin (x)^2+cos(x)^2)

    ans

    1

    1. 1- x2

    1 x

    simplify ((1-x^2)/(1-x))

    ans =

    x+1

    simple

  • 8/3/2019 MATH15L Coursewares

    84/215

    simple

    simple(E) searches for the symbolic expressions

    simplest form; that is, an expression that has thefewest character.

    Syntax: r = simple (S)

    Ex. Apply the simple and simplify commands

    1. log (xy)2. cos (3cos-1(x))

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

    Substitution

  • 8/3/2019 MATH15L Coursewares

    85/215

    Substitution

    subs used for symbolic substitution in a symbolic

    expression or matrix

    Syntax: R = subs (S, old, new)

    Ex. Given f(x) = x3+4x2-3x+5 Find:

    1. f(4)

    2. f(2z)

    3. f(x+1)

    Solving Equations

  • 8/3/2019 MATH15L Coursewares

    86/215

    Solving Equations

    If S is a symbolic expression solve (S) attempts to find

    values of the symbolic variable is S for which S is zero

    Syntax: g = solve (eq)

    g = solve (eq, var)

    Ex. >>solve (2*x^2-x-6=0)

    Solve the ff equations:

    x2+9y4=0

    e2x + 3ex =543. y2 + 3y + 2 = 0 solve for y

    4. b2 + 8c + 2b = 0, solve for c, then solve for b.

    Solving a Systems of Equations

  • 8/3/2019 MATH15L Coursewares

    87/215

    Solving a Systems of Equations

    [a, b, c, ] = solve(eq1, eq2, eq3, )

    Ex.

    1. 6x + 2y = 14

    3x + 7y = 31

    2. x + 6y = a2 x 3 y = 9

    Diff ti ti

  • 8/3/2019 MATH15L Coursewares

    88/215

    Differentiation

    MathC

    ommand MATLABC

    ommanddiff(f) or diff(f, x)

    diff(f, a)

    diff(f, b, 2)2

    2

    db

    fd

    da

    df

    dx

    df

  • 8/3/2019 MATH15L Coursewares

    89/215

    Examples:

    Differentiate the following functions:1.

    2.

    3.

    )sin( 2xdx

    d

    6

    3

    3

    y

    dy

    d

    222

    2

    3xyyx

    dy

    d

    Li it f F ti

  • 8/3/2019 MATH15L Coursewares

    90/215

    Limit of a Function

    MathC

    ommand MATLABC

    ommandlimit(f)

    limit(f, x, a) or limit(f, a)

    limit(f, x, a, right)

    limit(f, x, a, left)

    pax

    f(x)lim

    pax

    f(x)lim

    ax

    f(x)limp

    0x

    f(x)limp

    Example:

  • 8/3/2019 MATH15L Coursewares

    91/215

    Example:

    Evaluate the following:

    1.

    2.

    3.

    4.

    125x

    102xlim 35x

    p

    9x

    3xlim

    23x

    p

    h

    sinxh)sin(xlim

    0x

    p

    x

    sinlim

    0x

    x

    p

  • 8/3/2019 MATH15L Coursewares

    92/215

    5.

    6. and

    7.

    p x

    1lim

    0x

    p x

    1lim

    0x

    2

    2

    1x 1)sin(x

    1xlim

    p

    h

    sinxh)sin(xlim

    0h

    p

    Integration

  • 8/3/2019 MATH15L Coursewares

    93/215

    Integration

    MathC

    ommand MATLABC

    ommandint(f) or int(f, x)

    int(f, y)

    int(f, a, b) or int(f, x, a, b)

    int(f, y, a, b)

    f(x)dx

    y)dyf(x,

    b

    a

    f(x)dx

    b

    a

    y)dyf(x,

  • 8/3/2019 MATH15L Coursewares

    94/215

    Examples:

    Evaluate the following:1.

    2.

    3.

    4.

    dxx5

    xcosxdxsin4

    y)dycos(xy

    2

    1

    dyy

    1

  • 8/3/2019 MATH15L Coursewares

    95/215

    5.

    6.dxe

    0

    x2

    g

    1

    0

    lnzdzz

  • 8/3/2019 MATH15L Coursewares

    96/215

    ARRAYS AND MATRICES

    CREATING ARRAYS

  • 8/3/2019 MATH15L Coursewares

    97/215

    CREATING ARRAYS

    Type the elements inside a pair of square

    brackets, separating the elements inside with

    a space or a comma.Example:

    >>A = [10 3 4 6] or

    >>A = [10, 3, 4, 6]

    A. ROW VECTOR

  • 8/3/2019 MATH15L Coursewares

    98/215

    B. COLUMN VECTOR

    Separate the elements by semicolons or

    create a row vector first and then use the

    transpose notation ( ) which converts a row

    vector into a column vector, or vice versa.Example:

    >>B=[5; 3; 6; 0; 2] or

    >>B=[5, 3, 6, 0, 2]

  • 8/3/2019 MATH15L Coursewares

    99/215

    Another way is to type a left bracket and thefirst element, press ENTER, type the secondelement, press ENTER, and so on until youtype the last element followed by the rightbracket.

    Example:

    >>B=[5

    3

    6

    0

    2]

  • 8/3/2019 MATH15L Coursewares

    100/215

    C. MATRICES

    Type the matrix row by row, separating the

    elements in a given row with spaces or

    commas and separating the rows with

    semicolons.Example:

    To create , type

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

    -

    !

    42-1

    347A

    APPENDING ARRAYS

  • 8/3/2019 MATH15L Coursewares

    101/215

    APPENDING ARRAYS

    Array can be created by appending one arrayto anther.

    Illustration:

    1. Let array1 = [4, 6, 2] and

    array2 = [2, 5]. Type

    >>array3 = [array1, array2]

    2. Let and

    Typing >>C = [A , B]

    -

    ! 9-07

    62-4A

    -

    ! 15-

    42B

    SPECIAL WAY OF CREATING

  • 8/3/2019 MATH15L Coursewares

    102/215

    SPECIAL WAY OF CREATING

    MATRICES

    1. Using :

    The colon ( : ) generates a vector of

    regularly spaced elements. Typing>>x = [m: q: n]

    creates a vector x with first value m and last

    value n with a spacing q. The last value isless than n if m n is an integer not multiple

    of q.

  • 8/3/2019 MATH15L Coursewares

    103/215

    Example:>>x = [2: 2: 8]

    >>y = [1: 3: 11]

    >>z = [20: 2: 10]

    If q is omitted, it is presumed to be 1.

    Example:

    >>w = [3: 2]

    2. Using linspace

  • 8/3/2019 MATH15L Coursewares

    104/215

    g p

    Linspace command creates a linearly

    spaced row vector by specifying the numberof elements rather than the increment. The

    syntax >>x = [a, b, n] means creating a

    vector x where a and b are the lower and

    upper limits, respectively and n is thenumber of elements.

    Example:

    >>linspace (5, 8, 31).It contain 31 elements. If n is omitted, the

    spacing is 1.

  • 8/3/2019 MATH15L Coursewares

    105/215

    3. Using logspace

    It creates an array of logarithmically spacedelements. The syntax is

    >>logspace (a, b, n)

    where n is the number of elements between

    10a and 10b.

    Example:

    >>x = logspace (1, 1, 6)

    If n is omitted, the number of elements

    defaults to 50.

    SOME USEFUL ARRAY

  • 8/3/2019 MATH15L Coursewares

    106/215

    SOME USEFUL ARRAY

    FUNCTIONS

    Functions Descriptions

    magic(n) creates an n x n matrix where the

    sum of its diagonal, rows and

    columns are equal

    eye(n) creates an n x n identity matrix

    ones(n) creates an n x n matrix of ones

    ones(m,n) creates an m x n matrix of ones

    zeros(n) creates an n x n matrix of zeros

    zeros(m,n) creates an m x n matrix of zeros

    size(A) returns a row vector [m, n]

  • 8/3/2019 MATH15L Coursewares

    107/215

    ( ) [ ]

    containing the sizes of the m x n

    array Alength(A) computes either the number of

    elements of A if A is a vector or the

    largest value of m or n if A is an m x

    n matrixsum(A) sums the elements in each column

    of the array A and returns a row

    vector containing the sumssort(A) sorts each column of the array A in

    ascending order and returns an

    array the same size as A

  • 8/3/2019 MATH15L Coursewares

    108/215

    max(A) returns the algebraically largestelement in A if A is a vector.

    Returns a row vector containing

    the largest elements in each

    column if A is a matrix

    min(A) same as max(A) but returns

    minimum values

    diag(A) returns the main diagonal of A

  • 8/3/2019 MATH15L Coursewares

    109/215

    Practice Set:

    1. Let A = [1, 10, 6, 4; 7, 2, 5, 11;12, 0, 0, 8; 1, 3, 5, 6].

    Find: sum (A), max(A), min(A), length(A),

    size(A), sort(A), diag(A)

    2. Let B = magic(6). Verify that the sum of the

    rows, columns and diagonals are equal.

    3. Create an identity matrix with a size as

    matrix A in problem 1.

    ARRAY ADDRESSING/INDEXING

  • 8/3/2019 MATH15L Coursewares

    110/215

    ARRAY ADDRESSING/INDEXING

    Array indices are the row and columnnumbers of an element in an array and are

    used to keep track of the arrays elements.

    Illustration:

    Address Description

    v(2) refers to 2nd element in the vector v

    A(3,4) refers to the element in row 3,

    column 4

    v(:) represents all the row or column

    elements of the vector v

    v(1:3) represents the 1st through 3rd

  • 8/3/2019 MATH15L Coursewares

    111/215

    elements of v

    A(:, 2) denotes all the elements in the 2nd

    column of A

    A(:, 1:4) denotes all the elements in the 1st

    through 4th column of A

    A(3, :) denotes all the elements in the 3 rd

    row of A

    A(2:4, :) denotes all the elements in the 2nd

    through 4th row of AA(2:3,1:3) denotes all the elements in the 2nd

    through 3rd row that are also in the

    1st

    Practice Set:

  • 8/3/2019 MATH15L Coursewares

    112/215

    1. Let v = [4, 2, 6, 0, 8] and A = [1, 7, 4, 0;

    1, 5, 3, 2; 3, 1, 8, 5]. Determine theoutput of the following:

    a. v(5)

    b. v(2:4)

    c. A(2,4)

    d. A(3,2)

    e. A(:, 3)

    f. A(:, 2:4)g. A(2,:)

    h. A(2:3, :)

  • 8/3/2019 MATH15L Coursewares

    113/215

    i. A(2:3, 3:4)

    j. A(2,4) = 6

    k. A(1, 5) = 2

    l. B = A(:, 4: 1:2)

    m. C = [1 1 1]; B(2, :) = C

    ARRAY OPERATIONS

  • 8/3/2019 MATH15L Coursewares

    114/215

    (Element-by-element operations)

    Symbols Operations

    + Scalar-array addition

    Scalar-array subtraction

    + Array addition

    Array subtraction

    .* Array multiplication

    ./ Array right division

    .\ Array left division

    .^ Array exponentiation

    Practice Set:

  • 8/3/2019 MATH15L Coursewares

    115/215

    1. Given:

    A = [2, 3] B = [6, 7] b = 6Find: A + b, A b, A + B, A B, A .* B,

    A ./ B, A .\ B, A .^ b, A .^ B

    2. Given:

    Find: A + B, C + D, A + C, B A, C B

    3-21

    06-2

    7-53

    A !

    14-0

    1050

    2-31-

    B !

    2-14-

    6-53C !

    000000D !

    1-2 43

  • 8/3/2019 MATH15L Coursewares

    116/215

    3. Given:

    Find: 4A, 2B,

    4. Given:

    Find:AB, BA,CA, A

    C

    2-4

    12A !

    65-

    43B !

    B2

    1A

    151-

    240

    1-32

    A !

    213

    02-2

    1-5-1

    B !

    5-4-

    6-4

    20

    C !

    MATRIX OPERATIONS

  • 8/3/2019 MATH15L Coursewares

    117/215

    MATRIX OPERATIONS

    Applies the same rule in ordinary matrices

    operations in Mathematics.

    Note:

    1. + and apply the same rule as in element-by-element operations.

    2. A/B = A*B-1 , where B-1 is the inverse of B.

    3. A^2 = A*A4. AB is not defined .

    Example:

  • 8/3/2019 MATH15L Coursewares

    118/215

    Let M = [1, 3, 6; 2, 4, 0; 5, 8, 9],

    N = [4, 2; 6, 3; 1, 5] and O = [2, 2, 1;3, 4, 0; 1, 3, 7]. Find:

    a. MN

    b. M2

    c. Show that MM-1=1

    d. Show that M/O = MO-1

    Use the command inv(A) to evaluate the

    inverse of matrix A.

    Determinants

  • 8/3/2019 MATH15L Coursewares

    119/215

    Use the command det(A) to evaluate the

    determinant A.

    Examples:

    Evaluate the following determinants:

    a. c.

    b.129-

    53-

    143

    211

    1-32

    05-2-3

    7046-

    4-503

    4520

    Solution of LinearSystems of

    Al b i E ti

  • 8/3/2019 MATH15L Coursewares

    120/215

    Algebraic Equations

    Consider a linear system of algebraicequations with n equations and n

    unknowns:

    Solution of LinearSystems of

    Al b i E ti

  • 8/3/2019 MATH15L Coursewares

    121/215

    Algebraic Equations

    In these equations, aij and bi areconstants, and the unknowns are

    xi. We can rewrite the equations as:

    where

    Solution of LinearSystems of

    Al b i E ti

  • 8/3/2019 MATH15L Coursewares

    122/215

    Algebraic Equations

    We can find all the unknowns in the vectorx bydoing a few simple matrix manipulations. If we

    premultiply both sides of the matrix equation by

    the inverse of the A matrix we get:

    which gives us our solution.

    An Example

  • 8/3/2019 MATH15L Coursewares

    123/215

    p

    Consider the system of 3 equations and 3

    unknowns:

    An Example

  • 8/3/2019 MATH15L Coursewares

    124/215

    p

    Using MatLab:

    >> A=[2 3 -1;-1 2 3;0 1 2]

    A =

    2 3 -1

    -1 2 30 1 2

    >> b=[-1 9 5]'

    b =

    -1

    9

    5

    An Example

  • 8/3/2019 MATH15L Coursewares

    125/215

    p

    Using MatLab:

    >> x=inv(A)*b

    x =

    -11

    2

    Eigenvalues and Eigenvectors

  • 8/3/2019 MATH15L Coursewares

    126/215

    Eigenvalues and Eigenvectors

    Many problems present themselves in terms ofan eigenvalue problem:

    In this equation A is an n-by-n matrix, v is a

    non-zero n-by-1 vector and is a scalar (which

    may be either real or complex). Any value of

    for which this equation has a solution is knownas an eigenvalue of the matrix A. It is

    sometimes also called the characteristic value.

    Eigenvalues and Eigenvectors

  • 8/3/2019 MATH15L Coursewares

    127/215

    Eigenvalues and Eigenvectors

    The vector, v, which corresponds to this value iscalled an eigenvector. The eigenvalue problem

    can be rewritten as

    If v is non-zero, this equation will only have asolution if

    Eigenvalues and Eigenvectors

  • 8/3/2019 MATH15L Coursewares

    128/215

    Eigenvalues and Eigenvectors

    This equation is called the characteristic

    equation ofA, and is an n

    th

    order polynomial in with n roots. These roots are called the

    eigenvalues ofA. We will only deal with the

    case of n distinct roots, though they may be

    repeated. For each eigenvalue there will be aneigenvector for which the eigenvalue equation

    is true.

    Example

  • 8/3/2019 MATH15L Coursewares

    129/215

    Example

    If

    then the characteristic equation is

    Example

  • 8/3/2019 MATH15L Coursewares

    130/215

    Example

    and the two eigenvalues are

    All that's left is to find the two eigenvectors. Let's find

    the eigenvector, v1, associated with the eigenvector,1, first.

    Example

  • 8/3/2019 MATH15L Coursewares

    131/215

    Example

    so clearly

    and the first eigenvector is any 2 element column vectorin which the two elements have equal magnitude and

    opposite sign.

    where k1 is an arbitrary constant. Note that we didn't

    have to use +1 and -1, we could have used any two

    quantities of equal magnitude and opposite sign.

    Example

  • 8/3/2019 MATH15L Coursewares

    132/215

    Example

    Going through the same procedure for the secondeigenvalue:

    Using Matlab

  • 8/3/2019 MATH15L Coursewares

    133/215

    Using Matlab

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

    0 1

    -2 -3

    [v,d]=eig(A)v =

    0.7071 -0.4472

    -0.7071 0.8944

    d =

    -1 0

    0 -2

    Using Matlab

  • 8/3/2019 MATH15L Coursewares

    134/215

    Using Matlab

    The eigenvalues are the diagonal of the "d" matrix;1=-1, 2=-2. The eigenvectors are the columns of the

    "v" matrix.

    Note that MatLab chose different values for v1,1, etc...,but that the ratio of v1,1 to v1,2 and the ratio of v2,1 to v2,2are the same as our solution.

    (MatLab chooses the values such that the sum of thesquares of the elements of the eigenvector equals

    unity).

  • 8/3/2019 MATH15L Coursewares

    135/215

    Sequence & Series

    Sequence & Series

  • 8/3/2019 MATH15L Coursewares

    136/215

    Sequence & Series

    Arithmetic SeriesLet An = {1, 3, 5, 7, 9}. Find the value of

    Matlab Code:

    >> A=1:2:9;

    >> s=sum(A)

    s =

    25

    Sequence & Series

  • 8/3/2019 MATH15L Coursewares

    137/215

    Sequence & Series

    Matlab Code:>> n=1:26

    >> s=sum((5)./((n+5)+3))

    s =

    7.0018

    Sequence & Series

  • 8/3/2019 MATH15L Coursewares

    138/215

    Sequence & Series

    Matlab Code:

    Sequence & Series

  • 8/3/2019 MATH15L Coursewares

    139/215

    Sequence & Series

    Matlab Code:

  • 8/3/2019 MATH15L Coursewares

    140/215

    Eigenvalues and

    Eigenvectors

    Solution of LinearSystems of

    Algebraic Equations

  • 8/3/2019 MATH15L Coursewares

    141/215

    Algebraic Equations

    Consider a linear system of algebraicequations with n equations and n

    unknowns:

    Solution of LinearSystems of

    Algebraic Equations

  • 8/3/2019 MATH15L Coursewares

    142/215

    Algebraic Equations

    In these equations, aij and bi areconstants, and the unknowns are

    xi. We can rewrite the equations as:

    where

    Solution of LinearSystems of

    Algebraic Equations

  • 8/3/2019 MATH15L Coursewares

    143/215

    Algebraic Equations

    We can find all the unknowns in the vectorx bydoing a few simple matrix manipulations. If we

    premultiply both sides of the matrix equation by

    the inverse of the A matrix we get:

    which gives us our solution.

    An Example

  • 8/3/2019 MATH15L Coursewares

    144/215

    Consider the system of 3 equations and 3

    unknowns:

    An Example

  • 8/3/2019 MATH15L Coursewares

    145/215

    Using MatLab:

    >> A=[2 3 -1;-1 2 3;0 1 2]A =

    2 3 -1

    -1 2 30 1 2

    >> b=[-1 9 5]'

    b =

    -1

    9

    5

    An Example

  • 8/3/2019 MATH15L Coursewares

    146/215

    Using MatLab:

    >> x=inv(A)*b

    x =

    -11

    2

    Eigenvalues and Eigenvectors

  • 8/3/2019 MATH15L Coursewares

    147/215

    g g

    Many problems present themselves in terms ofan eigenvalue problem:

    In this equation A is an n-by-n matrix, v is a

    non-zero n-by-1 vector and is a scalar (which

    may be either real or complex). Any value of

    for which this equation has a solution is knownas an eigenvalue of the matrix A. It is

    sometimes also called the characteristic value.

    Eigenvalues and Eigenvectors

  • 8/3/2019 MATH15L Coursewares

    148/215

    g g

    The vector, v, which corresponds to this value iscalled an eigenvector. The eigenvalue problem

    can be rewritten as

    If v is non-zero, this equation will only have asolution if

    Eigenvalues and Eigenvectors

  • 8/3/2019 MATH15L Coursewares

    149/215

    g g

    This equation is called the characteristic

    equation ofA, and is an nth order polynomial in

    with n roots. These roots are called the

    eigenvalues ofA. We will only deal with the

    case of n distinct roots, though they may be

    repeated. For each eigenvalue there will be aneigenvector for which the eigenvalue equation

    is true.

    Example

  • 8/3/2019 MATH15L Coursewares

    150/215

    p

    If

    then the characteristic equation is

  • 8/3/2019 MATH15L Coursewares

    151/215

    Example

  • 8/3/2019 MATH15L Coursewares

    152/215

    p

    so clearly

    and the first eigenvector is any 2 element column vectorin which the two elements have equal magnitude and

    opposite sign.

    where k1 is an arbitrary constant. Note that we didn't

    have to use +1 and -1, we could have used any two

    quantities of equal magnitude and opposite sign.

    Example

  • 8/3/2019 MATH15L Coursewares

    153/215

    p

    Going through the same procedure for the secondeigenvalue:

    Using Matlab

  • 8/3/2019 MATH15L Coursewares

    154/215

    g

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

    0 1

    -2 -3

    [v,d]=eig(A)v =

    0.7071 -0.4472

    -0.7071 0.8944

    d =

    -1 0

    0 -2

    Using Matlab

  • 8/3/2019 MATH15L Coursewares

    155/215

    g

    The eigenvalues are the diagonal of the "d" matrix;1=-1, 2=-2. The eigenvectors are the columns of the

    "v" matrix.

    Note that MatLab chose different values for v1,1, etc...,but that the ratio of v1,1 to v1,2 and the ratio of v2,1 to v2,2are the same as our solution.

    (MatLab chooses the values such that the sum of thesquares of the elements of the eigenvector equals

    unity).

  • 8/3/2019 MATH15L Coursewares

    156/215

    MATLAB

    GRAPHICS2-D

    FIGURE WINDOWS

  • 8/3/2019 MATH15L Coursewares

    157/215

    MATLAB directs graphics output toa window called figure that is

    separate from the command

    window. The figure function

    creates figure windows.

    Example: >>figure

    2-D Plotting

  • 8/3/2019 MATH15L Coursewares

    158/215

    The plot function is used to produce two-dimensional curves, using x- and y-data

    matrices specified by the user.

    plot(xdata,ydata,clm)

    You can plot multiple lines at once, using

    pairs of x- and y-data, or triples of x, y.

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

    Examples:

  • 8/3/2019 MATH15L Coursewares

    159/215

    Examples:

    >> x = 0:10 ;>> y = 2*x + 3;

    >> plot(x,y)

    >> y1 = 4*x 2;>> y2 = x + 2;

    >> plot(x,y1,x,y2)

    Adding a Grid

  • 8/3/2019 MATH15L Coursewares

    160/215

    GRID ON creates a

    grid on the current

    figure

    GRID OFF turns off

    the grid from thecurrent figure

    GRID toggles the

    grid state

    Color, Line Style and Marker

  • 8/3/2019 MATH15L Coursewares

    161/215

    The user can specify the color, linestyle and marker of a graph. If not, a bluesolid line without marker symbols, isproduced. Some of them are:

    COLORS MARKERS LINE STYLES

    y yellow . point -- dashed

    m magenta x x-mark -. dashdot

    c cyan * star : dotted

    r red + plus

    g green o circle ^ triangle (up)b blue s square p pentagram

    w white d diamond h hexagram

    k black v triangle (down)

  • 8/3/2019 MATH15L Coursewares

    162/215

    Graph a red sine wave

    >> x = 0:0.1:2*pi;

    >> y = sin(x);

    >> plot(x,y,r)

    >> grid on

  • 8/3/2019 MATH15L Coursewares

    163/215

    Try to graph the following using the different line styles,

    markers and colors.

    1. Graph y = 2cos3x

    2. Graph the exponential function, logarithmic function,

    inverse trigonometric function, hyperbolic function withappropriate domain.

    Adding Additional Plots to a Figure

  • 8/3/2019 MATH15L Coursewares

    164/215

    By default, plot deletes existing lines and resets all axisproperties when a new line is drawn.

    HOLD ON holds the current plot

    HOLD OFF releases hold on the current plot

    HOLD toggles the hold state

  • 8/3/2019 MATH15L Coursewares

    165/215

    >> x = 0:0.1:2*pi;

    >> y = sin(x);

    >> plot(x,y,r)

    >> grid on>> hold on

    >> plot(x, exp(-x),b:*)

    Controlling Viewing Area

  • 8/3/2019 MATH15L Coursewares

    166/215

    LEFT mouse button zoom in

    (x2)

    RIGHT mouse button zoomout (x )

    Double-click LEFT zoom out

    completely

    ZOOM ON allows user toselect viewing area

    ZOOM OFF prevents

    zooming operations

    ZOOM toggles the zoomstate

    ZOOM using the figure tool bar

    GRAPH ANNOTATIONS

  • 8/3/2019 MATH15L Coursewares

    167/215

    ExampleType the following commands in the command window.

    >>x=0:pi/20:2*pi;

    >>y=sin(x);

    >>plot(x,y,bs-,linewidth,2)

    >>hold on

    >>y1=cos(x);

    >>plot(x,y1,r>:,linewidth,2)

    ADDING A TITLE TO A GRAPH

  • 8/3/2019 MATH15L Coursewares

    168/215

    1. Using the Title Option on

    the Insert Menu.

    (i) Click the Insert menu inthe Figure window menu bar

    and choose Title.

    (ii) Enter the text of the label

    and click anywhere in thefigure background to close

    the text entry box.

    There are several ways to add title to a graph:

    ADDING A TITLE TO A GRAPH

  • 8/3/2019 MATH15L Coursewares

    169/215

    2. Using the Property Editor to

    Add a Title.

    (i) Double click on the axes on

    the graph to open the

    Property Editor.

    (ii) Select the Style panel and

    type in the text of your title in

    the Title entry box.

    (iii) ClickApply.

    ADDING A TITLE TO A GRAPH

  • 8/3/2019 MATH15L Coursewares

    170/215

    3. Using the Title Function.

    To add a title to a graph at the MATLAB command prompt,

    use the title function.

    Example:

    >> title(Graph of Sine and Cosine Functions)

  • 8/3/2019 MATH15L Coursewares

    171/215

    ADDING A LEGEND TO A GRAPH

  • 8/3/2019 MATH15L Coursewares

    172/215

    There are two ways to add legend to a graph:

    1. Using the Legend Option on the Insert Menu.

    - Click on the Insert menu and choose Legend.

    2. Using the Legend Function.To add a legend to a graph at the MATLAB command

    prompt, use the legend function.

    Example:>>legend( Sine Function , Cosine Function )

    ADDING AXES LABELS TO A GRAPH

    There are three ways to add labels to a graph:

  • 8/3/2019 MATH15L Coursewares

    173/215

    There are three ways to add labels to a graph:

    1. Using the Label Options on the Insert Menu.(i) Click on the Insert menu and choose label

    option that corresponds to the axes you want

    to label.

    (ii) Enter the text of the label, or edit the text of

    an existing label.

    2. Using the Property Editor.

    (i) Start plot editing mode.

    (ii) Double click on the axes on the graph to

    open the Property Editor.(iii) Select the Labels panel and enter the text of

    the label in the appropriate text entry box.

    (iv) ClickApply.

    3 C

    ADDING AXES LABELS TO A GRAPH

  • 8/3/2019 MATH15L Coursewares

    174/215

    3. Using the Label Commands.

    To add x, y and z axis labels to a graph use xlabel,ylabel and zlabel functions.

    Example:

    >>xlabel( x-axis,FontSize,16)

    ADDING TEXT ANNOTATIONS TO A

    GRAPH

  • 8/3/2019 MATH15L Coursewares

    175/215

    1. Creating Text Annotations in Plot Editing Mode.

    (i) Click on the Insert menu and choose the Text

    option or click the text button in the figure

    window toolbar.(ii) Position the cursor where you want to add a

    text annotation in the graph and click.

    (iii) Enter a text.

    (iv) Click anywhere in the figure background to

    close the text entry box.

    ADDING TEXT ANNOTATIONS TO A

    GRAPH

  • 8/3/2019 MATH15L Coursewares

    176/215

    2. Adding Text Annotations with the text or gtextCommand.

    To create annotations using text function, the text

    and its location must be specified using the x and y

    coordinates.Example:

    a. >>str1(1) = {Sine Function:}

    >>str1(2) = {y=sin(x)}

    >>text(3,0.5,str1)

    b. >>str2(1) = {Cosine Function: }

    >>str2(2) = {y1=cos(x)}

    >>text(0.3,-0.6,str2)

    ADDING TEXT ANNOTATIONS TO A GRAPH

  • 8/3/2019 MATH15L Coursewares

    177/215

    SAVING FIGURES

  • 8/3/2019 MATH15L Coursewares

    178/215

    You can savefigures with SaveorSave Asthrough the Filemenu on theFigure Window.

    This will create a.fig file.

    Displaying Multiple Plots per

    Figure

  • 8/3/2019 MATH15L Coursewares

    179/215

    g

    Format: subplot(m,n,i)

    This function breaks the figure window into m-by-n

    matrix of small subplots and selects the ith subplot

    for the current plot.

    Examples:

    1. >> subplot(2,2,1) 2. >> subplot(2,3,1)

    >> subplot(2,2,2) >> subplot(2,3,2)

    >> subplot(2,2,3) >> subplot(2,3,3)>> subplot(2,2,4) >> subplot(2,3,4)

    >> subplot(2,3,5)

    >> subplot(2,3,6)

    MULTIPLE PLOTSPER FIGURE

  • 8/3/2019 MATH15L Coursewares

    180/215

    subplot(2,2,i)

    where i = 1 to 4subplot(2,3,i)

    where i = 1 to 6

    1 2

    3 4

    1 2 3

    4 5 6

    Example

    Type the following commandsin the command window.

  • 8/3/2019 MATH15L Coursewares

    181/215

    >>x=0:pi/20:2*pi;>>y=sin(x);

    >>subplot(1,2,1)

    >>plot(x,y,bs-,linewidth,2)

    >>y1=cos(x);>>subplot(1,2,2)

    >>plot(x,y1,r>:,linewidth,2)

  • 8/3/2019 MATH15L Coursewares

    182/215

    BASIC PLOTTING

    COMMANDS

    ezplot

    l t i t f ti l tt f

  • 8/3/2019 MATH15L Coursewares

    183/215

    ezplot is an easy to use function plotter for

    algebraic and transcendental functions,

    parametric equations, implicit and explicit

    functions.

    ezplot(f)

    plots the expression f = f(x) over the

    default domain -2T < x < T

    ezplot(f,[a,b])

    plots f = f(x) over a < x < b

    Examples:

    >> subplot(2,3,1)

  • 8/3/2019 MATH15L Coursewares

    184/215

    >> ezplot(cos(x))

    >> subplot(2,3,2)

    >> ezplot(cos(x),[0, pi])

    >> subplot(2,3,3)

    >> ezplot(1/y-log(y)+log(-1+y)+x-1)

    >> subplot(2,3,4)

    >> ezplot(x^2+y^2-4)

    >> subplot(2,3,5)

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

    >> ezplot(sin(t),cos(t))

  • 8/3/2019 MATH15L Coursewares

    185/215

    POLAR CURVESPolar in polar coordinates can be created using the

  • 8/3/2019 MATH15L Coursewares

    186/215

    p g

    polar(t,r,S) function, where t is the angle vector in radians, ris the radius vector, and S is an optional character string

    describing the color, marker symbol, and/or line style.

    Example

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

    >>r=sin(2*t).*cos(2*t);

    >>polar(t,r)

    >>title(Polar Plot)

    HISTOGRAMHistogram illustrates the distribution of values in a vector.

    hist(y) draws a 10 bin histogram for the data in vector y

  • 8/3/2019 MATH15L Coursewares

    187/215

    Example>>x=-2.9:0.2:2.9; %specify the bins to use

    >>y=randn(5000,1);%generate 5000 random points>>hist(y,x) %draw the histogram

    >>title(Histogram of Gaussian Data)

    hist(y) draws a 10-bin histogram for the data in vector y.

    hist(y,n), where n is a scalar, draws a histogram with n bins.hist(y,x), where x is a vector, draws a histogram using the

    bins specified in x.

    PIE CHARTStandard pie charts can be created using the pie(a,b) function,

  • 8/3/2019 MATH15L Coursewares

    188/215

    where a is a vector of values and b is an optional logical

    vectors describing a slice or slices to be pulled out of the pie

    chart. The pie3 function renders the pie chart with a 3-D

    appearance.

    Example

    >>a=[0.5 1 1.6 1.2 0.8 2.1];>>subplot(1,2,1)

    >>pie(a,a==max(a)); %produces

    chart a and pull out the biggest

    slice.

    >>subplot(1,2,2)>>explode=[1 0 0 0 0 0 ];

    >>pie(a,explode) % Which part is

    pulled out?

    BAR GRAPHSBar graphs display vector or matrix data. By default, a bar

    graph represents each element in matrix Bars in a 2-D graph

  • 8/3/2019 MATH15L Coursewares

    189/215

    graph represents each element in matrix. Bars in a 2-D graph,

    created by barfunction, are distributed along the x-axis witheach element in a column drawn at a different location. All

    elements in a row are clustered around the same location on

    the x-axis.

    Example

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

    >> subplot(1,2,1)

    >> bar(y)

    >> subplot(1,2,2)

    >>bar3(y)

    SPECIALIZED PLOT COMMANDS

  • 8/3/2019 MATH15L Coursewares

    190/215

    The following are some other specialized plotcommands:

    area

    pie3

    rose

    stairs

    stem3

    quiver

    compass

    feather

  • 8/3/2019 MATH15L Coursewares

    191/215

    MATLAB

    GRAPHICS3-D

    ezsurf

    ezsurf(f) creates a graph of f(x,y), where f is a

  • 8/3/2019 MATH15L Coursewares

    192/215

    string that represents a mathematicalfunction of two variables, such as x and y.

    Example:

    >> subplot(1,2,1)

    >> ezsurf('x^2+y^2')

    >> subplot(1,2,2)

    >> ezsurf('x^2-y^2')

    ezmeshezmesh(f) creates a graph of f(x,y), where f is a

    symbolic expression that represents a mathematical

  • 8/3/2019 MATH15L Coursewares

    193/215

    symbolic expression that represents a mathematical

    function of two variables, such as x and y.

    Example:

    >> subplot(1,2,1)

    >> ezmesh('x^2+y^2')

    >> subplot(1,2,2)

    >> ezmesh('x^2-y^2')

    OTHER PLOTTING COMMANDS

  • 8/3/2019 MATH15L Coursewares

    194/215

    mesh

    contour

    contour3

    waterfall

    surf

    plot

    FIGURE WINDOW TOOLS

  • 8/3/2019 MATH15L Coursewares

    195/215

    ENJOY MATLAB GRAPHICS !

  • 8/3/2019 MATH15L Coursewares

    196/215

    Introduction to MATLAB

  • 8/3/2019 MATH15L Coursewares

    197/215

    Programming

    Programs are contained in m-files

    - Plain files not binary files produced by word

  • 8/3/2019 MATH15L Coursewares

    198/215

    Plain files not binary files produced by word

    - Files must have an .m extension m-files must be in path

    When you call an M-file function from either the command lineor

    from within another M-file, MATLAB parses the function andstores it

    in memory.

    This prevents MATLAB from having to reparse a function eachtime you call it during a session.

    The compiled function remains in memory until you clear itusing the

    CLEAR command, or until you quit MATLAB.

    TWO TYPES OF M-FILES1 S i t

  • 8/3/2019 MATH15L Coursewares

    199/215

    1. Scripts

    - Automate long sequences of commands

    2. Functions

    - provide extensibility to MATLAB. They allow you to add newfunctions to the existing functions

    Script M-files- Standard ASCII text files

  • 8/3/2019 MATH15L Coursewares

    200/215

    - Standard ASCII text files

    - Contains series of MATLAB expressions stored together in apredefined sequence.

    - Saved with an .m extension and are called by simply typingthe filename without the extension in the command window.

    Downside ofusing Scriptfiles:

    - All variables created are added to the workspace.

    - Variables already existing in the workspace may be overwritten

    Functions M-files- Functions are subprograms

  • 8/3/2019 MATH15L Coursewares

    201/215

    Functions are subprograms

    - Use input and output parameters to communicate with otherfunction

    Differences between Script & Function M-files:

    Structural Syntax - must contain keyword FUNCTION at thebeginning of the first line

    Function Workspaces, Inputs & Outputs- A function does not work with variables in the base MATLAB

    workspace.

    As a result, all information to be transferred between theMATLAB workspace and a function must bepassedas inputs

    & outputs.

    Structure of a Function M-file

  • 8/3/2019 MATH15L Coursewares

    202/215

    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;

    Keyword: function Function Name (same as file name .m)

    Output Argument(s) Input Argument(s)

    Online Help

    MATLAB

    Code

    output_value = mean(input_value) Command Line Syntax

    Inputs to Functions :

    Text Input and Output

  • 8/3/2019 MATH15L Coursewares

    203/215

    Inputs to Functions :

    input function can be used to prompt the user for numeric or

    string input

    Input parameters to functions are preferred

    Text output from functions:

    disp function for simple output

    fprintffunction for formatted output.

    Prompting for User InputTh i t f ti b d t t th f i

  • 8/3/2019 MATH15L Coursewares

    204/215

    The input function can be used to prompt the user for numeric

    or string input.

    Syntax: entry = input (TextDisplay)

    entry = input (TextDisplay, s )

    Examples:>> x = input (Enter a value for x)

    Enter a value for x %serves as a prompt on the screen thatsignifies that MATLAB is awaitingfor user

    response.

    >>yourName = input (Enter your name,s);%like the previous

    command but will return the entered string as a

    text variable rather than as a variable name or

    numerical value.

    Text Output with disp- Output to the command window is achieved with the disp

  • 8/3/2019 MATH15L Coursewares

    205/215

    Output to the command window is achieved with the disp

    functiondisp Simple to use. Provides limited control over appearance of

    output.

    Syntax: disp (variable)

    disp (text string)

    Examples:

    >>poly_roots = [ 1.2400 2.5600 5.6400 ]

    >> disp ('The roots of the cubic polynomial are')

    The roots of the cubic polynomial are

    >> disp (poly_roots)

    1.2400 2.5600 5.6400

    >> disp ('The roots of the cubic polynomial are') , disp (poly_roots)

    The roots of the cubic polynomial are

    1.2400 2.5600 5.6400

    disp Simple to use. Provides limited control over appearance ofoutput.

  • 8/3/2019 MATH15L Coursewares

    206/215

    Syntax: disp (variable)disp (text string)

    Examples:>>poly_roots = [ 1.2400 2.5600 5.6400 ]>> disp ('The roots of the cubic polynomial are')

    The roots of the cubic polynomial are>> disp (poly_roots)

    1.2400 2.5600 5.6400>> disp ('The roots of the cubic polynomial are') , disp (poly_roots)The roots of the cubic polynomial are

    1.2400 2.5600 5.6400

    Relational and Logical Operators

    Operators Description

  • 8/3/2019 MATH15L Coursewares

    207/215

    p p

    < Less than

    > Greater than

    = Greater than or equal to

    ~= Not equal to

    == Equal to

    & AND

    | OR

    ~ NOT

    xor Exclusive OR

    -Will output 1 for true conditions and 0 for false conditions

    - Can be used with scalars and arrays

    Other Logical built-in functions

    Operators Description

  • 8/3/2019 MATH15L Coursewares

    208/215

    all (A)

    Returns true if all elements in a vectorA aretrue.

    Returns false if one or more elements arefalse

    any (A)

    Returns 1 (true) if any element in a vectorA

    is true (nonzero).Returns 0 (false) if all elements are false.

    find (A)IfA is a vector, returns the indices of thenonzero elements

    find (A>d)IfA is a vector, returns the address of theelements that are larger than d (anyrelational operator can be used)

    SUMMARY

    Relational operators involve comparison of two values.

  • 8/3/2019 MATH15L Coursewares

    209/215

    The result of a relational operation is a logical (True/False)value.

    Logical operators combine (or negate) logical values to

    produce another logical value.

    Example : Analysis of temp dataThe following were the daily max temp in (F) in Washington during

    the month of April,2002.

  • 8/3/2019 MATH15L Coursewares

    210/215

    the month of April,2002.

    58 73 73 53 30 48 56 73 73 66 69 63 74 82 84 91 93 89 91 8059 69 56 64 63 66 64 74 63 69.

    Use relational logical operators to determine the following:a. The number of days the temp was above 75b. the number of days the temp was between 65 and 80

    Examples:

    >> r = [ 8 12 9 4 23 19 10 ]

  • 8/3/2019 MATH15L Coursewares

    211/215

    [ ]

    r =

    8 12 9 4 23 19 10

    >>s=r>t=r(s) % use s for addresses in vector r to create a vector t

    t=

    8 9 4 10

    >> w=r(r

  • 8/3/2019 MATH15L Coursewares

    212/215

    Example

  • 8/3/2019 MATH15L Coursewares

    213/215

    function areacircle

    r=input('Give radius of circle: ');

    a=pi*r^2;

    fprintf('The area of circle with radius %.2f is %.6f\n',r,a);

    end

    Flow control - selection

  • 8/3/2019 MATH15L Coursewares

    214/215

    The if-elseif-else construction

    if

    elseif

    else

    end

    if height>170disp(tall)

    elseif height

  • 8/3/2019 MATH15L Coursewares

    215/215

    teenager, adult and senior given as the input of the variableage.

    function check_age

    age=input('Enter your age: ')

    if age