You are on page 1of 215

in cooperation with

presents

Course Code: MATH15L Course Title: MATLAB Pre-requisite: Co-requisite: MATH 15 Credit: 1 unit Equivalent Course Codes: None Faculty:

Course Description
The course utilizes the capability of information technology to facilitate the understanding of basic mathematical principles and operations. A mathematical software (MATLAB) will be used to perform algebraic operations, differentiation, integration, matrix operations, graphic manipulation and some basic MATLAB programming for simulations and analysis.

Course Objectives and Relationship to Program Objectives


It is a laboratory course in mathematics. Its goals are to give the students sufficient understanding of MATLAB and its application for the purpose of developing students skill in solving problems and to apply their acquired learning in engineering applications.

It prepares students to recognize patterns and formulate rules as a first step to develop students skill for independent critical thinking. The course aims to develop the students zest for knowledge, application and appreciation of an orderly and logical solution as guided by the different principles undertaken in the course.

Course Coverage
Foundation and Fundamental Concepts Arrays and Matrices Symbolic Math Graphs Programming

Course Outcomes and Relationship to Program Outcomes:


A student completing this course should at a minimum be able to: perform polynomial operations such as multiplication and division. decompose rational polynomials into sum of partial fractions. perform the four fundamental operations on matrices as well as getting the determinant of square matrix.

solve systems of equations and polynomial equations. 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.

Course Evaluation
Points Long Tests Classroom Exercise/Hands on Exam Classroom Participation Portfolio 2 5 250 450 25% 45%

50

5%

Final Examination TOTAL

250 1000

25% 100%

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.

Portfolio Guidelines
No late Portfolio will be accepted. Use short black Clear Book.

Average Below 70 70-73.3 73.31-76.6 76.61-79.9 79.91-83.2

Grade 5.00 3.00 2.75 2.50 2.25

Average 83.21-86.5 86.51-89.8 89.81-93.1 93.11-96.4 96.41-100

Grade 2.00 1.75 1.50 1.25 1.00

Other course Policies


Attendance
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 regardless of class standing.

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 sustain these codes. It will be expected in this class that each of us will honor the commitments that we have made.

For this course the Honor Code 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.

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.

Computer Laboratory Guidelines


No student shall be allowed to enter the laboratory 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.

A strict one (1) computer to one (1) student ratio shall be observed. Students are not allowed to use external devices without the approval of the Deputy Director for Systems Administration. Students must notify the assign personnel in charge regarding any errors and/or breakages of facilities and/or equipment in their designated areas. No excessive noise. Using mobile phone or any musical instrument is strictly prohibited. Diskettes are not allowed. Accessing the internet is prohibited.

MATLAB BASICS

What is MATLAB?

- The name stands for MATrix LABoratory - MATLAB is a high-performance language for technical
computing. It integrates computation, visualization, and programming environment.

- MATLAB

is a modern programming language environment: it has sophisticated data structures, contains built-in editing and debugging tools, and supports object-oriented programming.

THE MATLAB SYSTEM

Development Environment The MATLAB Mathematical Function Library The MATLAB Language The MATLAB Application Program Interface (API)

Development Environment

- Set of tools and facilities that help use MATLAB


functions and files.

- Includes:
- MATLAB Desktop - Command Window - Command History - Editor and Debugger and browsers for viewing help - Workspace

MATLAB MATHEMATICAL FUNCTION LIBRARY

- This is a vast collection of computational algorithms


ranging from elementary functions Examples: > sum, sine, cosine, and complex arithmetic > sophisticated functions like matrix inverse, matrix eigenvalues, Bessel functions, and fast Fourier transforms.

MATLAB LANGUAGE
- This is a high-level matrix/array language with control flow statements, functions, data structures, input/output, and object-oriented programming features. - It allows both "programming in the small" to rapidly create quick and dirty throw-away programs, and "programming in the large" to create complete large and complex application programs.

GRAPHICS

- MATLAB has extensive facilities for displaying vectors


and matrices as graphs, as well as annotating and printing these graphs.

- It

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

- It also includes low-level functions.

MATLAB APPLICATION PROGRAM INTERFACE


- This is a library that allows you to write C and Fortran programs that interact with MATLAB. - It includes facilities for calling routines from MATLAB (dynamic linking), calling MATLAB as a computational engine, and for reading and writing MAT-files.

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

WORKSPACE BROWSER
- Consists of the set of variables during a MATLAB session and stored in memory

ARRAY EDITOR

- Use to edit the variables in the workspace. - Three ways to open: double click the variable in the
workspace browser, select the variable in the workspace and click open , use the openvar syntax

EDITOR/DEBUGGER

- Used to create and debug M-files, which are program


you write to run the MATLAB functions

Foundation and Fundamental Concepts

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 the right of the prompt. This cursor and the MATLAB prompt signify that MATLAB is waiting to perform a mathematical operation.

Commands for Managing a Session


clear who whos exist global help lookfor quit - Removes all the variables from the workspace. - Frees up system memory - Displays the list of variables currently in the memory. - Will display more details which include size, space, allocation and class of variables - Checks for existence of the variable. - Declares variable to be global. - Searches for help topic - Searches help entries for keyword - Stops the MATLAB

Help Features in MATLAB


helpbrowser Opens the help window

Displays the help document in the help function_name command window Displays the help document in helpwin function_name separate window doc function_name Displays detailed help document in separate window

Numeric Display Formats


- Controls the display output of the command window Common Format Functions format short long short e long e bank - Four decimal digits - Sixteen decimal digits - Five decimal digits plus exponent - Sixteen digits plus exponent - Two decimal digits

Mathematical Functions
Special Variables and Constants ans i,j Inf NaN pi - Most recent answer - The imaginary unit - Infinity - Undefined numerical result (not a number) - The number

Mathematical Functions
Elementary Functions
cos(x) sin(x) tan(x) acos(x) asin(x) atan(x) exp(x) sqrt(x) log(x) log10(x) Cosine Sine Tangent Arc cosine Arc sine Arc tangent Exponential Square root Natural Logarithm Common Logarithm abs(x) ceil(x) floor(x) round(x) rem(x) angle(x) conj(x) imag (x) real (x) primes (x) Absolute value Round towards + Inf Round towards - Inf Round Remainder after division Phase Complex Conjugate imaginary Real number Prime Number

Mathematical Functions
Scalar Arithmetic
Symbol + * / \ ^ Operation Addition Subtraction Multiplication Right Division Left Division Exponentiation

Mathematical Functions
Exponential and Logarithmic Functions
exponential Natural Logarithm Common Logarithm Square root exp (x) ln (x) log10 (x) = [ log10 (x) ] sqrt (x)

Example1: 2+34 In Command Window >>2 + 3 4 ans = 1 Example2: 6z3 In Command Window >> 6 / 3 ans = 2

Example3:

3z6
In Command Window >> 6 \ 3 ans = 0.5 MATLAB has assigned the answer to a variable called ans, which is an abbreviation for answer. A variable in MATLAB is a symbol used to contain a value.

MATLAB does not care about spaces for the most part. Spaces in the line improve its readability. When you want to calculate a more complex expression use parentheses, in the usual way, to indicate precedence. The mathematical operations represented by the symbols + * / \, and ^ follow a set of rules called precedence..

Mathematical expressions are evaluated starting from the left, with the exponentiation operation having the highest order of precedence, followed by multiplication and division with equal precedence, followed by addition and subtraction with equal precedence. Parentheses can be used to alter this order. Evaluation begins with the innermost pair of parentheses, and proceeds outward.

To avoid mistakes, you should feel free to insert parentheses wherever you are unsure of the effect precedence will have on the calculation. Example4: 4 3(23  14 .7  ) 6 3 .5 In Command Window >> (3*(23 + 14.7 (4 / 6))) / 3.5

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, the user can define them once and then call them by name.

Example5: Given: a = 2, A = 3 Find: a. 2a b. w=3A In Command Window >>a=2 a= 2 >>A=3;

When you write the semicolon ; at the end of a statement, the computer will not display the result of the command, and it will not echo the input. >>2*a ans = 4 >>w=3*A w= 9 MATLAB does not tell you the value of all the variables; it merely gives you their names. To find their values, you must enter their names at the MATLAB prompt.

>>a = 4 a= 4 >>2*a ans = 8 If you reuse a variable in the preceding example, or assign a value to one of the special variables, its prior value is overwritten and lost. However, any other expressions computed using the prior value do not change.

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;

>> sin (alpha) ans = 0.9880 A pair of parentheses is used after the functions name to enclose the value called the functions argument that is operated on by the function. >> sin (beta) ans = 0.9866 >> sin (gamma) ans = 0.5661

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.

Example of Formating: 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.

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

>> format long e >> pi ans = 3.14159265358979e+000 >> format bank >> pi ans = 3.14 To return to default format >> format >> pi ans = 3.1416

Most interesting is the format rat: it yields a rational approximation of a real number, that is a fraction that approximates a given number. >> format rat >>pi ans = 355/113 >>format >>355/113 ans = 3.1416

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.  3( 2)  3

 12  3(2)
d 58

8  ( 4) z 4  ( 2) 25


5T x! 2

e. Given:

Determine: i. y = sin x ii. when y = 1, what is z = sin-1 y cos1 0.3 g. e h. cos (T / 2) 2. Suppose that x = 3 and y = 4. Use MATLAB to compute the following.

1 a. 1  5 x

1

b. 3 T3 y x2 c. 4 x  8

d. 4( y  5 ) 3x  6 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. a c

x ! 1

b.

ba s! dc

c. r !

1 1 1 1 1    a b c d

d.

1f y ! ab c 2

4.

Evaluate the following expressions MATLAB, for the values x = 5 + 8i, y = 6 + 7i. a. u = x + y b. v = xy c. w = x / y d. z = ex e. r ! y f. s = xy2

in

Polynomial Algebra
Partial fraction Roots of Equation Polynomial and Symbolic Conversion

Consider f(x) = 12x4 3x2 + x + 7. This function f can be written in array form called coefficient array, that is, f = [12, 0, -3, 1, 7]. Command conv(a, b) Description Computes the product of the two polynomials described by the coefficient arrays a and b. The two polynomials need not be the same degree. The result is the coefficient array of the product polynomial.

Example 1. (2x+1)(3x-5)

Answer 6x^2 -7x -5

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

X^5-x^3+x^26x-3

[q, r] = deconv(num, den)

Example
3 2

12x  5 x 2 3x  7 x  4 2x  x  6 x 2 2x  7 x  6
3 2

Computes the result of dividing a numerator polynomial, whose coefficient array is num, by a denominator polynomial represented by the coefficient array den. Answer Q= 4x+11  2x  3 R= 59x 41 Q= x+3 R= 9x -18

poly(r)

Computes the coefficients of the polynomial whose roots are specified by the vector r. The result is a row vector that contains the polynomials coefficients arranged in descending order of power

Example X1=1 X2=-1 X1=1 X2=2 X3=3

Answer 1 0 1 -6 -1 => X^2-1 11 -6 => x^3-6x^2+11x-6

[r,p,k] = residue(a,b)

Finds the residues, poles and direct term of a partial fraction expansion of the ratio polynomials a(x) / b(x) Answer

Example

5x  7 3 2 x  x x2
2x  4x  2x  x  7 x3  2 x 2  x  2
4 3 2

2 1 1   x 1 x 1 x  2 2 1 1 2x    x 1 x 1 x  2

polyval(a, x)

Evaluates a polynomial at specified values of its independent variable x, which can 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

roots(a)

Computes the roots of a polynomial specified by the coefficient array a. The result is a column vector that contains the polynomials roots. Answer X1=1 X2=-1 X1=1 X2=2 X3=3

Example X^2-1 x^3-6x^2 +11x-6

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 symbolic polynomial Example: poly2sym([1 0 -2 -5]) is x^3-2*x-5

SYMBOLIC PROCESSING Process of obtaining answers in the form of expressions Terms used to describe how MATLAB performs operations or evaluates mathematical expressions in the way, for examples, that humans do algebra with pencil and paper.

Symbolic Object Symbolic object is a data structure that stores a string representation of the symbol. The two ways to create 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.

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.

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.

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 sym function. Example: >> pi = sym(pi) >> fraction = sym(1/4) >> sqroot2 = sym(sqrt(2))

pretty The pretty function displays symbolic output in a format 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 )

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 S to a numeric object. Syntax: r = double (S) >> sqroot2 = sym (sqrt (2)); >> z = 6* sqroot2 >> double (z)

SIMPLIFICATION: Commands collect (s) horner (s) simplify (s) expand (s) factor (s) simple (s)

collect collect (f) views f as a polynomial in its symbolic variables, say x, and collects all the coefficients with the 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 specify the variable in which to collect terms if there is more than one candidate.

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

horner horner (f) transforms a sumbolic polynomial f into 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 factor (S) factors the expression S which can be positive integer, an array of symbolic expressions, or an array of symbolic integers. Syntax: factor (S) Ex. 1. factor (x^3 - y^3)

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 simple(E) searches for the symbolic expressions simplest form; that is, an expression that has the fewest 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 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 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 =54 3. y2 + 3y + 2 = 0 solve for y 4. b2 + 8c + 2b = 0, solve for c, then solve for b.

Solving a Systems of Equations [a, b, c, ] = solve(eq1, eq2, eq3, ) Ex. 1. 6x + 2y = 14 3x + 7y = 31 2. x + 6y = a 2x 3y = 9

Differentiation
Math Command

df dx

MATLAB Command diff(f) or diff(f, x) diff(f, a) diff(f, b, 2)

df da 2 d f

db 2

Examples: Differentiate the following functions: 1. d sin( x 2 )

dx

d3 6 2. y 3 dy
3. d 2

dy

y  3xy

Limit of a Function
Math Command lim f(x)
x p0

MATLAB Command limit(f) limit(f, x, a) or limit(f, a) limit(f, x, a, right) limit(f, x, a, left)

lim f(x)
x pa

lim f(x)
x pa


lim f(x)
x pa


Example: Evaluate the following: 1. lim 2x  10 x p5 x 3  125

sin x 2. lim x p0 x

x3 3. lim 2 x p3 x 9
sin(x  h)  sinx 4. lim x p0 h

5.

sin(x  h)  sinx lim h p0 h

1 and 1 6. lim lim x p0 x x p0 x

x 1 7. lim 2 x p1 sin(x  1)


2

Integration
Math Command

f(x)dx f(x, y)dy


b

MATLAB Command int(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
a b

f(x, y)dy
a

Examples: Evaluate the following: 1. x 5 dx 2. 3. 4.

sin 4 xcosxdx

cos(xy  y)dy
2

1 dy y

5.

0 g

zlnzdz

6.

e
0

x2

dx

ARRAYS AND MATRICES

CREATING ARRAYS
A. ROW VECTOR
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]

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]

Another way is to type a left bracket and the first element, press ENTER, type the second element, press ENTER, and so on until you type the last element followed by the right bracket. Example: >>B=[5 3 6 0 2]

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: 7 4 3 To create A ! , type 1 - 2 4 >>A=[7, 4, 3; 1, 2, 4]

APPENDING ARRAYS
Array can be created by appending one array to anther. Illustration: 1. Let array1 = [4, 6, 2] and array2 = [2, 5]. Type >>array3 = [array1, array2] 2. Let A ! 4 - 2 6 and B ! 2 4 - 5 1 7 0 - 9 Typing >>C = [A , B]

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 is less than n if m n is an integer not multiple of q.

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 Linspace command creates a linearly spaced row vector by specifying the number of 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 the number of elements. Example: >>linspace (5, 8, 31). It contain 31 elements. If n is omitted, the spacing is 1.

3. Using logspace It creates an array of logarithmically spaced elements. 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 FUNCTIONS


Functions magic(n) Descriptions creates an n x n matrix where the sum of its diagonal, rows and columns are equal creates an n x n identity matrix creates an n x n matrix of ones creates an m x n matrix of ones creates an n x n matrix of zeros creates an m x n matrix of zeros

eye(n) ones(n) ones(m,n) zeros(n) zeros(m,n)

size(A)

returns a row vector [m, n] containing the sizes of the m x n array A length(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 matrix sum(A) sums the elements in each column of the array A and returns a row vector containing the sums sort(A) sorts each column of the array A in ascending order and returns an array the same size as A

max(A)

min(A) diag(A)

returns the algebraically largest element in A if A is a vector. Returns a row vector containing the largest elements in each column if A is a matrix same as max(A) but returns minimum values returns the main diagonal of A

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
Array indices are the row and column numbers of an element in an array and are used to keep track of the arrays elements. Illustration: Address v(2) A(3,4) v(:) Description refers to 2nd element in the vector v refers to the element in row 3, column 4 represents all the row or column elements of the vector v

represents the 1st through 3rd 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 3rd row of A A(2:4, :) denotes all the elements in the 2nd through 4th row of A A(2:3,1:3) denotes all the elements in the 2nd through 3rd row that are also in the 1st v(1:3)

Practice Set: 1. Let v = [4, 2, 6, 0, 8] and A = [1, 7, 4, 0; 1, 5, 3, 2; 3, 1, 8, 5]. Determine the output 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, :)

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 (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: 1. Given: A = [2, 3] B = [6, 7] b = 6 Find: A + b, A b, A + B, A B, A .* B, A ./ B, A .\ B, A .^ b, A .^ B 2. Given: -1 3 - 2 3 5 -7 A ! 2 -6 1 2 0 -3

B! 0

5 10 1

0 -4

C!

3 5 -6 -4 1 -2

D!

0 0 0 0 0 0

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

3. Given: A !

2 -1 4 -2

B!

3 4 -5 6

1 Find: 4A, 2B, A  B 2


4. Given: 1 - 5 -1 2 3 -1 0 2 A ! 0 4 2 B ! 2 -2 0 C ! 4 -6 3 1 2 -4 -5 -1 5 1 Find:AB, BA, CA, AC

MATRIX OPERATIONS
Applies the same rule in ordinary matrices operations in Mathematics. Note: 1. + and apply the same rule as in elementby-element operations. 2. A/B = A*B-1 , where B-1 is the inverse of B. 3. A^2 = A*A 4. AB is not defined .

Example: 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
Use the command det(A) to evaluate the determinant A. Examples: Evaluate the following determinants: a. - 3 5 c. 0 2 5 4 b.

- 9 12 2 3 -1 1 1 2 3 4 1

3 0 5 -4 -6 4 0 7 3 -2 -5 0

Solution of Linear Systems of Algebraic Equations


Consider a linear system of algebraic equations with n equations and n unknowns:

Solution of Linear Systems of Algebraic Equations


In these equations, aij and bi are constants, and the unknowns are xi. We can rewrite the equations as: where

Solution of Linear Systems of Algebraic Equations


We can find all the unknowns in the vector x by doing 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
Consider the system of 3 equations and 3 unknowns:

An Example
Using MatLab: >> A=[2 3 -1;-1 2 3;0 1 2] A= 2 3 -1 -1 2 3 0 1 2 >> b=[-1 9 5]' b= -1 9 5

An Example
Using MatLab: >> x=inv(A)*b x= -1 1 2

Eigenvalues and Eigenvectors


Many problems present themselves in terms of an 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 known as an eigenvalue of the matrix A. It is sometimes also called the characteristic value.

Eigenvalues and Eigenvectors


The vector, v, which corresponds to this value is called an eigenvector. The eigenvalue problem can be rewritten as

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

Eigenvalues and Eigenvectors


This equation is called the characteristic equation of A, and is an nth order polynomial in with n roots. These roots are called the eigenvalues of A. We will only deal with the case of n distinct roots, though they may be repeated. For each eigenvalue there will be an eigenvector for which the eigenvalue equation is true.

Example
If

then the characteristic equation is

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

and the first eigenvector is any 2 element column vector in 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
Going through the same procedure for the second eigenvalue:

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
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,2 are the same as our solution. (MatLab chooses the values such that the sum of the squares of the elements of the eigenvector equals unity).

Sequence & Series

Sequence & Series


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

Matlab Code: >> A=1:2:9; >> s=sum(A) s= 25

Sequence & Series

Matlab Code: >> n=1:26 >> s=sum((5)./((n+5)+3)) s= 7.0018

Sequence & Series

Matlab Code:

Sequence & Series

Matlab Code:

Eigenvalues and Eigenvectors

Solution of Linear Systems of Algebraic Equations


Consider a linear system of algebraic equations with n equations and n unknowns:

Solution of Linear Systems of Algebraic Equations


In these equations, aij and bi are constants, and the unknowns are xi. We can rewrite the equations as: where

Solution of Linear Systems of Algebraic Equations


We can find all the unknowns in the vector x by doing 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
Consider the system of 3 equations and 3 unknowns:

An Example
Using MatLab: >> A=[2 3 -1;-1 2 3;0 1 2] A= 2 3 -1 -1 2 3 0 1 2 >> b=[-1 9 5]' b= -1 9 5

An Example
Using MatLab: >> x=inv(A)*b x= -1 1 2

Eigenvalues and Eigenvectors


Many problems present themselves in terms of an 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 known as an eigenvalue of the matrix A. It is sometimes also called the characteristic value.

Eigenvalues and Eigenvectors


The vector, v, which corresponds to this value is called an eigenvector. The eigenvalue problem can be rewritten as

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

Eigenvalues and Eigenvectors


This equation is called the characteristic equation of A, and is an nth order polynomial in with n roots. These roots are called the eigenvalues of A. We will only deal with the case of n distinct roots, though they may be repeated. For each eigenvalue there will be an eigenvector for which the eigenvalue equation is true.

Example
If

then the characteristic equation is

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

and the first eigenvector is any 2 element column vector in 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
Going through the same procedure for the second eigenvalue:

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
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,2 are the same as our solution. (MatLab chooses the values such that the sum of the squares of the elements of the eigenvector equals unity).

MATLAB GRAPHICS 2-D

FIGURE WINDOWS
MATLAB directs graphics output to a window called figure that is separate from the command window. The figure function creates figure windows. Example: >>figure

2-D Plotting
The plot function is used to produce twodimensional 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: >> 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
GRID ON creates a grid on the current figure GRID OFF turns off the grid from the current figure GRID toggles the grid state

Color, Line Style and Marker


The user can specify the color, line style and marker of a graph. If not, a blue solid line without marker symbols, is produced. Some of them are:
COLORS y yellow m magenta c cyan r red g green b blue w white k black MARKERS . point x x-mark * star + plus o circle s square d diamond v triangle (down) LINE STYLES -dashed -. dashdot : dotted ^ p h triangle (up) pentagram hexagram

Graph a red sine wave >> x = 0:0.1:2*pi; >> y = sin(x); >> plot(x,y,r) >> grid on

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 with appropriate domain.

Adding Additional Plots to a Figure


By default, plot deletes existing lines and resets all axis properties 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

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


ZOOM ON allows user to select viewing area ZOOM OFF prevents zooming operations ZOOM toggles the zoom state LEFT mouse button zoom in (x2) RIGHT mouse button zoom out (x ) Double-click LEFT zoom out completely ZOOM using the figure tool bar

GRAPH ANNOTATIONS
Example Type 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


There are several ways to add title to a graph:
1. Using the Title Option on the Insert Menu. (i) Click the Insert menu in the Figure window menu bar and choose Title. (ii) Enter the text of the label and click anywhere in the figure background to close the text entry box.

ADDING A TITLE TO A GRAPH


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) Click Apply.

ADDING A TITLE TO A GRAPH


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)

ADDING A LEGEND TO A GRAPH


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: 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) Click Apply.

ADDING AXES LABELS TO A GRAPH


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


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


2. Adding Text Annotations with the text or gtext Command. 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

SAVING FIGURES
You can save figures with Save or Save As through the File menu on the Figure Window. This will create a .fig file.

Displaying Multiple Plots per Figure


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) >> subplot(2,2,2) >> subplot(2,2,3) >> subplot(2,2,4)

2. >> subplot(2,3,1) >> subplot(2,3,2) >> subplot(2,3,3) >> subplot(2,3,4) >> subplot(2,3,5) >> subplot(2,3,6)

MULTIPLE PLOTS PER FIGURE

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

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

Example Type the following commands in the command window. >>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)

BASIC PLOTTING COMMANDS

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

POLAR CURVES
Polar in polar coordinates can be created using the polar(t,r,S) function, where t is the angle vector in radians, r is 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)

HISTOGRAM
Histogram illustrates the distribution of values in a vector. 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.
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)

PIE CHART
Standard pie charts can be created using the pie(a,b) function, 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 GRAPHS
Bar graphs display vector or matrix data. By default, a bar graph represents each element in matrix. Bars in a 2-D graph, created by bar function, are distributed along the x-axis with each 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


The following are some other specialized plot commands:

area pie3 rose stairs

stem3 quiver compass feather

MATLAB GRAPHICS 3-D

ezsurf
ezsurf(f) creates a graph of f(x,y), where f is a string that represents a mathematical function 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')

ezmesh
ezmesh(f) creates a graph of f(x,y), where f is a 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


mesh contour contour3 waterfall surf plot

FIGURE WINDOW TOOLS

ENJOY MATLAB GRAPHICS !

Introduction to MATLAB

Programming

Programs are contained in m-files 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 line or from within another M-file, MATLAB parses the function and stores it in memory. This prevents MATLAB from having to reparse a function each time you call it during a session. The compiled function remains in memory until you clear it using the CLEAR command, or until you quit MATLAB.

TWO TYPES OF M-FILES


1. Scripts - Automate long sequences of commands 2. Functions - provide extensibility to MATLAB. They allow you to add new functions to the existing functions

Script M-files
Standard ASCII text files Contains series of MATLAB expressions stored together in a predefined sequence. Saved with an .m extension and are called by simply typing the filename without the extension in the command window.

Downside of using Script files: - All variables created are added to the workspace. - Variables already existing in the workspace may be overwritten

Functions M-files
Functions are subprograms Use input and output parameters to communicate with other function

Differences between Script & Function M-files: Structural Syntax - must contain keyword FUNCTION at the beginning 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 the MATLAB workspace and a function must be passed as inputs & outputs.

Structure of a Function M-file


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

Output Argument(s) function y = mean(x)

% MEAN Average or mean value. Online Help % 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); MATLAB Code if m == 1 m = n; end y = sum(x)/m; output_value = mean(input_value) Command Line Syntax

Text Input and Output


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 fprintf function for formatted output.

Prompting for User Input


The input function can be used to prompt the user for numeric or string input. Syntax: entry = input (Text Display) entry = input (Text Display, s ) Examples: >> x = input (Enter a value for x) Enter a value for x %serves as a prompt on the
response.

screen that signifies that MATLAB is awaiting for user

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

Relational and Logical Operators


Operators < > <= >= ~= == & | ~ xor Description Less than Greater than Less than or equal to Greater than or equal to Not equal to Equal to AND OR NOT 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 all (A) Description Returns true if all elements in a vector A are true. Returns false if one or more elements are false Returns 1 (true) if any element in a vector A is true (nonzero). Returns 0 (false) if all elements are false. If A is a vector, returns the indices of the nonzero elements If A is a vector, returns the address of the elements that are larger than d (any relational operator can be used)

any (A) find (A) find (A>d)

SUMMARY
Relational operators involve comparison of two values. 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 data The following were the daily max temp in (F) in Washington during the month of April,2002. 58 73 73 53 30 48 56 73 73 66 69 63 74 82 84 91 93 89 91 80 59 69 56 64 63 66 64 74 63 69. Use relational logical operators to determine the following: a. The number of days the temp was above 75 b. the number of days the temp was between 65 and 80

Examples: >> r = [ 8 12 9 4 23 19 10 ] r= 8 12 9 4 23 19 10 >>s=r<=10 %checks which r elements are smaller or equal to 10 s= 1 0 1 1 0 0 1 >>t=r(s) % use s for addresses in vector r to create a vector t t= 8 9 4 10 >> w=r(r<=10) % previous operations can be done in one step w= 8 9 4 10

fprint & sprintf

Example
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


The if-elseif-else construction
if <logical expression> <commands> elseif <logical expression> <commands> else <commands> end

if height>170 disp(tall) elseif height<150 disp(small) else disp(average) end

Example:
The following script file will returns one of the following messages: teenager, adult and senior given as the input of the variable age. function check_age age=input('Enter your age: ') if age<=18 disp('teenager') elseif age<=52 disp('adult') else disp('senior') end

You might also like