Professional Documents
Culture Documents
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.
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
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%
250 1000
25% 100%
Portfolio Guidelines
No late Portfolio will be accepted. Use short black Clear Book.
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.
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.
Development Environment The MATLAB Mathematical Function Library The MATLAB Language The MATLAB Application Program Interface (API)
Development Environment
- Includes:
- MATLAB Desktop - Command Window - Command History - Editor and Debugger and browsers for viewing help - Workspace
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
- It
includes high-level functions for two-dimensional and three-dimensional data visualization, image processing, animation, and presentation graphics.
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
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
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
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
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)
2. (x^2-3)(x^3+2x+1)
X^5-x^3+x^26x-3
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
[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
sym2poly
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.
Differentiation
Math Command
df dx
df da 2 d f
db 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
lim f(x)
x pa
lim f(x)
x pa
lim f(x)
x pa
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.
Integration
Math Command
f(x)dx
a b
f(x, y)dy
a
sin 4 xcosxdx
cos(xy y)dy
2
1 dy y
5.
0 g
zlnzdz
6.
e
0
x2
dx
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]
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.
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, :)
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
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
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
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.
Example
If
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 Code:
Matlab Code:
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
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.
Example
If
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).
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
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.
>> x = 0:0.1:2*pi; >> y = sin(x); >> plot(x,y,r) >> grid on >> hold on >> plot(x, exp(-x),b:*)
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)
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.
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)
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)
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.
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)
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')
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.
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.
% 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
%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
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
-Will output 1 for true conditions and 0 for false conditions - Can be used with scalars and arrays
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
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
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