Instru Instructo ctor: r: Dr. D B Gur Gurung ung
Introductory MATLAB Kathmandu University University Lecture Note for M.Phil. in Mathematics, 2012
0.1 0.1
Intr In trodu oduct ctio ion n
• MATLAB is an interactive matrix based system for scientific and engineering numerical computation computation and visualization visualization..
• It is a powerful tool that might solve complex numerical problems in a fraction of time required by other programming language such as FORTRAN or C.
• The name MATLAB stands for MATrix LABoratory, because every input in MATLAB
has to writ writee in Matrix. Matrix. Colum Column n or row row matri matrix, x, wh whic ich h consi consists sts of a collec collecti tion on of data data values organized into column or row, known as an array is is the fundamental unit of data in MATLAB program. So, an array is is the column vector or row vector in any MATLAB program.
1 2 Column Vector A = .. . n
;
Row Row Vecto ectorr B =
1
2 . .. n
× ; 1 n
n×1
1 3 × 4 Order Order Matr Matrix ix C = 5
2 3 4 6 7 8 9 10 11 12
3×4
and 1 The 1
Order Matrix = 12 × 1 Order
× 1 order matrix is termed as scalar .
• Arrays are classified as vector and matrix . A vector is an array with only one dimension, and a matrix is an array with two or more dimensions.
• The size of an array is specified as the number of rows and the number of columns in
the array with the number number of rows rows mention mentioned ed first. first. Indivi Individua duall elemen elements ts in an array array are addressed addressed by particular element. element. For example, in the above above arrays C(2,3) is 7 but C(4) is 2, because in this notation, by default, MATLAB addresses column-wise.
MATLAB variable is a region of memory containing an array that is known by a • A MATLAB user-specified name. In the above example, A, B and C are MATLAB variables.
MATLAB variable name must begin with a letter followed by any combination of letters, number nu mberss and the undersco underscore re charac character. ter. Only Only the first 63 charac characters ters are signifi significan cantt in MATLA MATLAB B 7.x. 7.x. Only Only the first 31 charac characters ters are signifi significan cantt in MATLA MATLAB B 6.5 or earlier earlier version.
0.2 0.2
Acce Access ssin ing g MATL MATLAB AB
Start:
• Access MATLAB from the menu or click the MATLAB icon on the desktop. > pops up (in command window). • MATLAB command prompt > > pops Quit:
• Type quit or exit after the command prompt • Click on respective close (×) button. 0.3 0.3
> >. >.
MATL MATLAB AB Wind Windo ows
• The Command Window • The Command History Window • The Current Directory Window • The Editor/Debug Window • The Workspace • The Figure Window 0.4
Enter Entering ing Vectors ectors and Matric Matrices es
Scalar: >> 5 ans = 5
Vectors: (a) Row Vector >> A = [1 2 3 4] A = 1 2 3
4
OR >> A = [1,2 [1,2,3 ,3,4 ,4] ] A = 1 2 3
(b) Column Vector
4
0.2 0.2
Acce Access ssin ing g MATL MATLAB AB
Start:
• Access MATLAB from the menu or click the MATLAB icon on the desktop. > pops up (in command window). • MATLAB command prompt > > pops Quit:
• Type quit or exit after the command prompt • Click on respective close (×) button. 0.3 0.3
> >. >.
MATL MATLAB AB Wind Windo ows
• The Command Window • The Command History Window • The Current Directory Window • The Editor/Debug Window • The Workspace • The Figure Window 0.4
Enter Entering ing Vectors ectors and Matric Matrices es
Scalar: >> 5 ans = 5
Vectors: (a) Row Vector >> A = [1 2 3 4] A = 1 2 3
4
OR >> A = [1,2 [1,2,3 ,3,4 ,4] ] A = 1 2 3
(b) Column Vector
4
>> B = [1 2 3 4]’ B = 1 2 3 4 >> B = [1;2 [1;2;3 ;3;4 ;4] ] B = 1 2 3 4
Matrix >> C = C = 1 4 7 OR >> C = C = 1 4 7 OR >> C = 4,5,6 7,8,9] C = 1 4 7 OR >> C = 4 5 6 7 8 9] C = 1 4 7
[1,2,3 [1,2,3;4, ;4,5,6 5,6;7, ;7,8,9 8,9] ] 2 5 8
3 6 9
[1 2 3;4 5 6;7 8 9] 2 5 8
3 6 9
[1,2 1,2,3
2 5 8
3 6 9
[1 2 3
2 5 8
3 6 9
The following input creates a matrix, in particular, a row vector with increment of 1. >> A = [1:8] A = 1 2
3
4
5
6
7
8
Increment according to our desire: The following example makes an increment of 2. The syntax syntax reads as [start value:incremen alue:increment:end t:end value]. value]. If the increment increment is missing, it is 1 by default. >> A = [-5: [-5:2: 2:5] 5] A = -5 -3 -1
1
3
5
Others which generates linearly spaced vectors are linspace( ) and logspace( ): linspace(a,b,n)) generates a linearly spaced vector of length n from a to b. • linspace(a,b,n
Example 1 u = linsp linspac ace(0, e(0,20,5 20,5)) gener generate atess a row vector vector u = [0 5 10 15 20]. 20]. Thus Thus u = linspace(a,b,n) is the same as u = a:(b-a)/(n-1):b. a
logspace(a,b,n)) generates a logarithmically spaced vector of length n from 10 • logspace(a,b,n
to 10b .
Example 2 v = logs logsppace( ace(0,3 0,3,4 ,4)) gene generrates ates a row vect vector or v = [1 10 100 1000]. 1000]. Thus Thus logspace(a,b,n) is the same as 10.ˆlinspace(a,b,n). Ellipses If a statement is too long to type on a single line, it may be continued on successive lines by typing an ellipsis (. (. . .) at the end of the first line, line, and then contin continuing uing on the next next line. line. For example, the following two statements are identical. >> X = 1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6 + 1/7 + 1/8 + 1/9; >> X = 1 + 1/2 + 1/3 + 1/4 + 1/5 + ... 1/6 + 1/7 + 1/8 + 1/9;
Meanings Meanings of Comma(,), Comma(,), Colon(:) and Semicolon(;): Semicolon(;):
• Comman (,) or space bar is used to write the elements of a row. • Colon (:) is used for increment in a row vector. • Semicolo Semicolon n (;) is used for new row in a matrix. matrix. The other important important signific significan antt of semicolon(;) is not to display the answer in command window but retains the input in computer memory. This we can do as
>> A = [1 2 3;4 5 6;7 8 9]; >> 4 + 5 + 6 + 7 + 8; 8;
0.5
Arithm Arithmeti eticc Operat Operation ionss and and Built Built-in -in-fu -func nctio tions ns
MATLAB knows real and complex numbers i.e., 2, 3.2, 4 + 2i, 4 + 2j(i, j both will accept as imaginary unit), and number in exponential form e.g 2. 2.35 10−6 = 2.35e 35e 6, blank space must avoided.
×
−
Arithmetic Operations : Operations Meaning + addition subtraction multiplication left division / right division ˆ power
− ∗ \
Note the distinction between left division ( ) and right division (/). This you can distinct with 6 2 = 0.3333 and 6/2 = 3. These operations for addition, subtraction and multiplication are explicitly used in compatiable matrices for matrix addition, subtraction and multiplication respectively. Note that if A is a non singular square matrix, then Aˆ2 is same as A A. If b is compatiable column and respectively row vector, then
\
\
∗
1
• X = A \ b gives the solution of the linear system of equations AX = b, i.e., X = A− b. • X = b / A gives the solution of the linear system of equations XA = b, i.e., X = bA− . 1
Hierarchy of Arithmetic Operations: The hierarchy of arithmetic operations are in the following orders: 1. The contents of all parantheses are evaluated, starting from the innermost parantheses and working outward. 2. All exponentials are evaluated, working from left to right. 3. All divisions and multiplications are evaluated, working from left to right. 4. All additions and subtractions are evaluated, working from left to right.
Built-in-functions:
• If arbitrary built in functions for scalars, e.g. exp( ), sqrt( ), sin( ) are applied on matrix, they are evaluated componentwise.
• A few built in functions in MATLAB deal with the whole matrix and not only with its components, e.g. expm( ), sqrtm( ), logm( ).
• The name of all built-in MATLAB function starts with a small letter, and the arguments of the functions are stated in round bracket (.). For example, >> real(-3+2*i) ans = 2 >> imag(-3+2*j) ans = 7
Built-in-functions for Scalar: Commands Functions Commands abs( ) absolute value sqrt( ) real( ) real part imag( ) angle( ) phase angle conj( ) round( ) round to integer sign( ) floor( ) floor function ceil( ) exp( ) exponential function log( )
Functions square root imaginary part complex conjugate signum function ceiling function logrithmic function
>> sqrt(3) ans = 1.7321 By default, MATLAB produces 4 digits after decimal places. If we want the more digits after the decimal places, then do as >> format long >> sqrt(3) ans = 1.73205080756888 There are other format commands too.
Trigonometric functions: Commands Functions Commands Functions sin( ) sine cos( ) cosine tan( ) tangent cot( ) co-tangent sec( ) secant csc( ) cosecant asin( ) inverse sine acos( ) inverse consine sinh( ) hyperbolic sine asinh( ) inverse hyperbolic sine The angles given to these functions as arguments must be in radians.
Vector functions: Commands length( ) max( ) sum( ) sort( ) median( ) any( )
Functions Commands length of a vector norm( ) maximum min( ) sum of components prod( ) sorting mean( ) median std( ) any non-zero value! all( )
Functions norm of a vector minimum product of components mean standard deviation all non-zero value!
Matrix functions: Commands Functions Commands size( ) size rank( ) inv( ) inverse det( ) norm( ) norm cond( ) eig( ) eigenvalues chol( ) lu( ) LU decomposition qr( ) schur( ) schur complement hess( )
Functions rank determinant condition cholosky decomposition QR decomposition hessenberg form
Matrix built-in functions: Commands zeros( ) eye( ) rand( )
Functions Commands Functions matrix of zeros ones( ) matrix of ones identity matrix diag( ) create or extract diagonals uniform random value randn( ) normal random value
• zeros(m,n) produces m × n matrix of zeros and zeros(n) one of size n × n. • Take the online-help: > > help diag Example 3 Effects of diag command. >> B = [ones(3) zeros(3,2);zeros(2,3) 4*eye(2)] B = 1 1 1 0 0 1 1 1 0 0 1 1 1 0 0 0 0 0 4 0 0 0 0 0 4 >> diag(B)’ ans = 1 1 1 4 4 >> diag(B,1) ans = 1 1 0 0 >> diag(B,-2)’ ans = 1 0 0 >> >> >> >>
d = [2 4 6 8]; d1 = [-3 -3 -3]; d2 = [-1 -1]; D = diag(d) + diag(d1,1) + diag(d2,-2)
D = 2 0 -1 0
-3 4 0 -1
0 -3 6 0
0 0 -3 8
Addressing Matrix Components: the component amn of the matrix A = (aij )ij . Note that the numbering of the components starts from 1.
• A(m,n):
• A(m:n,p): the m until the nth row of the pth column of the matrix A. • A(:,n): the complete nth column of the matrix A. • A([m,n],:): the m and the nth row of the matrix A. • A([m,n],[p,q]): subarray of A whose first row elements are A(m,p), A(m,q) and second row elements are A(n,p), A(n, q).
• X(m): the mth component of the vector X. • X = X(n:-1:1): changes the order of the elements of the vector X of length n.
Some more built-in-functions:
• rot90() rotates a matrix by 90 degree. • fliplr(): flips a matrix from left to right. • flipud(): flips a matrix from up to down. • tril(): extracts the lower triangular part of a matrix. • triu(): extracts the upper triangular part of a matrix. • reshape(): changes the shape of a matrix. reshape(A,p,q) occurs as long as m × n = p × q where Amn. See the online help: > > help reshape
0.6
Array, Relational and Logical Operations
Array Operations: Element-by-element multiplication, division and exponentiation between two matrices or vectors of the same size are done by preceeding the corresponding arithmetic operations by a period (.). These relational operations result in a vector or matrix of the same size as the operands, with 1 where the relation is true and 0 where it is false. For example, >> [4 3 2]>[1 5 0] ans = 1 0 1 >> 5==3 ans = 0
Note that the equality sign = is used in an assignment statement , whereas == is used in a relation. Relations may be connected or quantified by logical operators.
Operations Meaning . element-by-element multiplication . element-by-element left division ./ element-by-element right division .ˆ element-by-element exponentiation
∗ \
Relational Operations: There are six relational operators in MATLAB. Operations Meaning < less than <= less than or equal > greater than >= greater than or equal == equal = not equal
∼
Logical Operations: These are the following logical operators in MATLAB. Operations Meaning & logical AND && logical AND with shorcut evaluation logical OR logical OR with shortcut evaluation Xor exclusive OR logical NOT
| || ∼
These operators work in a similar way as the relational operators and produces vectors or matrices of the same size as the operands, with 1 where condition is true and 0 where false. For example: >> (2==2)&(2>1) ans = 1 >> (2==3)&(2>1) ans = 0 >> (2==3)|(2>1) ans = 1
Differences between & and &&: The following are the two major differences between these two operators. & 1. Works between scalar and array values 2. Does not support partial evaluation or short cut evaluation
&& 1. Works between scalar values only 2. Support’s partial evaluation or short cut evaluation
Look at the following Matlab outputs for the differences: (a) >> ([2 3]==[2 3])&(3>4) (b)>> ([2 3]==[2 3])&&(3>4) (c) >> tic, (2==3)&(3>2),toc (d)>> tic, (2==3)&&(3>2),toc
Explanation: Suppose p is the statement ([2 3] == [2 3]) and q be the statement (3 > 4). The operator && will evaluate expression p and immediately return False value if p is false. If p is false, the operator never evaluates q , because the result of operator will be False regardless of the value of q . In contrast, the & operator always evaluates both p and q before returning an answer. Hierarchy of Operations: The order in which the operators in an expression are evaluated is: 1. All arithmetic operations in the order as described in hierarchy of arithmetic operations. 2. All relational operators (==, =, > , >=, < , <=) are evaluated, working from left to right.
∼
3. All
∼ are evaluated.
4. All & and && operators are evaluated, working from left to right.
| || and Xor opertors are evalueated, working from left to right.
5. All ,
MATLAB (Exercise - 1) MATLAB Interactive with Calculator 1. Try the calculation operations and built-in-functions:
• 3 + 4;
8/2; 8 2; 3ˆ3; (2*2 + 2*i); (2*2 + 2*i)-(2 + i); 2*2e+2; 2*2e-2; (2e+14/15); (2e+14)/15
\
• Absolute value: abs(-0.5), abs(2+2*j) Floor value: floor(4.5);
Ceiling value: ceil(4.45); Square root: sqrt(2); sqrt(-2); Real part: real(2 + 7i); Imaginary part: imag(2 - 3i); Signum function: sign(-3.2); sign(3.2); sign(0);
• Use also: exp(); sin(); tan(); • Try to understand the difference between:
sin() and sind()
2. Type in vectors:
• Enter the Vectors:
A = [5 2 1 4 0 3 10 9]. Also enter the elements of A in column
vector.
• Find:
length(A), max(A), min(A), norm(A), sort(A), mean(A), std(A), median(A), sum(A), prod(A).
3. Type in matrices:
• Enter the matrix: A = [2 sqrt(2) 4;0 1e-1 3;-2.1 1.732 2] • Find: size(A), rand(size(A)), inv(A), det(A), norm(A). 4. Assume that array C is defined as shown, and sub-arrays: 1.1 3.2 C = 0.6 1.1 1.3 0.6
−
determine the contents of the following 3.4 0.6 0.6 3.1 5.5 0.0
−
(a) C(2,:) (b) C(:,end) (c) C(1:2,2:end) (d) C(6) (e) C(4:end) (f) C(1:2,2:4) (g) C([1 3],2) (h) C([2 2],[3 3]) (i) C([1 3],:) = C([3, 1],:) 5. Determine the contents of array a after the following statements are executed: (a) a = [1 2 3;4 5 6;7 8 9]; a([3 1] , :) = a([1 3] , :); (b) a = [1 2 3;4 5 6;7 8 9]; a([3 1] , :) = a([2 2] , :); (c) a = [1 2 3;4 5 6;7 8 9]; a = a([2 2] , :); 6. Determine the contents of array a after the following statements are executed. (a) a = eye(3 , 3); b = [1 2 3]; a(2 , :) = b; (b) a = eye(3 , 3); b = [4 5 6]; a(: , 3) = b’; (c) a = eye(3 , 3); b = [7 8 9]; a(3 , :) = b([3 1 2]); (d) a = eye(3 , 3); b = [7 8 9]; a(: , 3) = b([3 1 2]); 7. Define variables (MATLAB distinguises between capital and small letters)
• a1 = 4; a2 = [4:2:17] - what’s the result?
• Find out the differences between a = a1 + 4 and a = a1 + 4; - What’s the consequence of ; after a statement. Enter the command who - What’s MATLAB answer?
• • Enter the command whos - What’s MATLAB answer? • Enter clear and afterwards who - What’s MATLAB answer now? 8. Matrix Operations:
• Define A = [2 1 1;3 2 3;1 4 9], B = 2*A, and b = [10 18 16]’ • Compute: size(A), size(b), length(b), length(A), A’, A + B, A - B, A*B, A.*B, A*b. If error is executed, try to find the reason. Type inv(A) - What’s the consequence of inv(A)?
• • Type inv(A)*b - What’s the result? What’s can you say about the result? • Type A\b - What’s the consequence of A\b? • Type A/b - What’s the consequence of A/b? • Is A\b = inv(A)*b? • Is A/b = b*inv(A)? • How can you get entry 100 in B(1,1)? • What’s the output of: diag(A)? And diag(b)? • What’s the output of eig(A)? What’s the output for [V,D] = eig(A)? Can you guess • •
the consequence of these results? Generation of special matrices: Try eye(3), zeros(2,3), ones(3,4), rand(3,3) and again rand(3,3). What is the output of C = [A,zeros(3,2);zeros(2,3),eye(2);1:5]? What is the output of C([1:3],[2,4])?
• What’s the output of:
A(1), A(4), A(1,1), A(1,:), A(:,3), C = A([1,2],:), D =
A(:,[1,2])
9. Consider the matrix
1 5 A = 9
2 3 4 6 7 8 10 11 12 13 14 15 16
(a) Enter it in the following three ways: (i) type in all 16 elements directly. (ii) since each row is in arithmetic progression, use the colon operator to enter each row. (iii) since each column is in arithmetic progression, use the colon operator (and the transpose operator) to enter each column. (b) Multiply the second row of A by -9/5, add it to the third row, and put the result back in the second row. Do, this all using one MATLAB statement. 10. The distance traveled by a ball falling in the air is given by the equation x = x 0 +v0 t+ 12 at2 . Use MATLAB to calculate the position of the ball at time t = 5 s if x0 = 10 m, v0 = 15 m/s, and a = 9.81 m/sec2 .
−
MATLAB (Exercise - 2) MATLAB Interactive Computation 1. Run time error: Errors due to indeterminate forms. The MATLAB output is NaN, that is not a number. (a) Evaluate the values of sinx x in the interval [-1, 1] considering the vectors x = ( 1 : 1)/3.
−
(b) Evaluate the values of sinx x in the interval [-1, 1] considering the vectors x = x+(x == 0) eps where initially x = ( 1 : 1)/3. Try to understand the outputs in (a) and (b).
∗
−
2. Equation of a straight line: The equation of a straight line is y = mx + c where m and c are constants. Compute the y-coordinates of a line with slope m = 0.5 and the intercept c = 2 at the following x-coordinates.
−
x = 0, 1.5, 3, 4, 5, 7, 9, and 10 3. Application: Write the following system of linear equation 3x + y + z = 3; 2x - 3y - z = -3; x + 2y + z = 4 in matrix form. Check whether the system is consistent or not. If consistent then use MATLAB to find the solution of this system. [Helpful builtin-functions: rank(A), and rank([A,b]) where A is the coefficient matrix and [A,b] is the augmented matrix.] 4. Exponential and Logarithms: The mathematical quantities ex , lnx and logx are calculated with exp(x), log(x) and log10(x) respectively. Calculate the following quantities. 2
2
2
5
• e ,√ ln(e ),log10(e ) and log10(10 ). •e . • Solve 3 = 17 for x and check the result.(The solution x = π 163
x
ln17 .) ln3
5. Trigonometry: The basic MATLAB trigonometric functions are sin, cos, tan, cot, sec and csc. The inverses e.g. arcsin, arctan etc are calculated with asin, atan etc. The same is true for hyperbolic functions. The argument of these functions must be in radian. Calculate the following quantities:
• sin • sin
π , cos π4 and 6 2 π + cos2 π6 . 6
tan π2 .
2
2
(Typing sin2 (x) for sin2 x will produce an error. Correct form is
(sin(x))ˆ2).
• y = cos h x − sin h x with x = 32π.
√ −
6. Complex Number: MATLAB recognizes the letter i and j as the imaginary unit 1. A complex number 2 + 5i may be input as 2 + 5i or 2 + 5*i in MATLAB. Compute the following quantities: 1+3i . 1 3i
• − •e
Can you check the result by hand calculation?
πi/4
. Check the Euler’s formula eix = cos x + i sin x by computing the right hand side too, i.e. cos( π4 ) + i sin( π4 ).
• Execute the command exp(π/2 ∗ i) and exp(π/2i). between the two results?
Can you explain the difference
7. Create a big matrix with submatrices: Enter the matrices. A =
2 6 3 9
;
B=
1 2 3 4
C =
;
−5 5 5
3
and then create a matrix G by putting matrices A, B and C given above, on its diagonal. (You are not allowed to enter the non-zero numbers explicitly).
2 3 G = 00 0
6 9 0 0 0 0 0
0 0 1 3 0 0
0 0 2 4 0 0
0 0 0 0 5 5
−
0 0 0 0 5 3
8. Manipulate a matrix: Do the following operations on matrix G created above in (6).
• Delete the last row and last column of the matrix. • Extract the first 4 × 4 submatrix from G. • Replace G(5,5) with 4. • What do you get if you type G(13) and hit return? Can you explain how MATLAB got that answer?
• What happens if you type G(12,1) = 1 and hit return? 9. See the structure of a matrix: Create a 20 × 20 matrix with the command A = ones(20). Now replace the 10 × 10 submatrix between rows 6:15 and columns 6:15 with zeros. See the structure of the matrix in terms of non-zero entries with the command spy(A). Set the 5 × 5 submatrices in the top right corner and bottom left corner to zeros and see the structure again.
10. Create a symmetric matrix: Create an upper triangular matrix with the following command: A = diag(1 : 6) + diag(7 : 11, 1) + diag(12 : 15, 2) Make sure you understand how this command works (see the online help on diag if required). Enter triu(A,1), triu(A,2) and triu(A,-1) – Can you guess the outputs? Now use the upper off-diagonal terms of A to make A a symmetric matrix with the following command: A = A + triu(A, 1) . 11. The geometric series: The sum of a geometric series 1 + r + r 2 + + r n approaches the limit 1−1 r for r < 1 as n . Create a vector n of 11 elements from 0 to 10. Take r = 0.5 and create another vector x = [r0 , r1 , , rn ] with the command x = r.ˆn. Now take the sum of this vector with the command S = sum(x)(S is the sum of the actual series). Calculate the limit 1−1 r and compare the computed sum S. Replace the procedure taking n from 0 to 50 and then from 0 to 100.
| |
→ ∞
· ··
·· ·
12. Solving Equations: The command solve(’f(x)’) solves an equation in one unknown f (x) = 0. The command [x, y] = solve(’f(x,y)’,’g(x,y)’) solves a system of equations in two unknowns, f (x, y) = 0, g(x, y) = 0. The calculations are based on symbolic calculations . The variables x, y,z,a,b,c are declared to be symbolic variables with the command
>> syms x y z a b c
(a) Use solve command to find the solutions of the following equations: (i) x 2 5x + 6 = 0 (ii) x 2 2x + 2 = 0 (iii) x3 x + 1 = 0 (iv) x3 2x 5 (v) xex = 1 Use > > double(ans) or > > eval(ans) in the ans you get in MATLAB output.
− − −
−
−
(b) Use solve command to solve the two equations simultaneously: (i) y 4x2 + 3 = 0, x2 /4 + y 2 1 = 0 (ii) x2 y2 = 3, x2 + y 2 = 13 (iii) x2 = 3xy 7, y = 2(x + 1)
−
−
−
−
0.7
Plotting
• The plots in MATLAB appear in the graphic/figure window. • MATLAB provides very good facilities for both 2-D and 3-D graphics.
It can produce
3-D mesh as well as 3-D faceted surface and 3-D contour plots.
• The most direct commands to produce a graph in 2-D and 3-D plot are the plot and plot3 commands respectively. The primary command for mesh, surface and contour plots are mesh surf, and contour respectively.
2-D Plot Command plot(xdata,ydata) where ydata are the values of y variable corresponding to x variable which are given as xdata. This command plots xdata along horizontal axis and ydata along vertical axis. xdata and ydata both are vectors having of same length.
Example 4 Plot the function y = x 2 Solution:
− 10x + 15, where x ∈ [0, 10].
>> x = [0:10]; % Creates vector x (xdata) >> y = x.^2 - 10.*x + 15; % Calculates y (ydata) >> plot(x,y)
Example 5 plot3() is a three-dimensional analogue of plot(). plot3(x,y,z), where x, y and z are three vectors of the same length, plots a curve in 3-space through the points whose coordinates are the elements of x, y and z. Use plot3() to plot the function f (x, y) = x3 3xy2 over the rectangular region 5 x 5, 5 y 5 . Solution:
− ≤ ≤ − ≤ ≤
>> >> >> >>
−
x = [-5:0.5:5]; % Creates vector x (xdata) y = x; % Creates vector y (ydata) z = x.^3 - 3.*x.*y.^2; % Calculates z (zdata) plot3(x,y,z)
Helpful built-in-functions used in plotting: The figures can be given titles, axes labeled and text placed within the figure with the following commands which take a string as argument. title() xlabel() ylabel() zlabel() gtext() text() grid Type >> help legend
figure title x-axis label y-axis label z-axis label place text on the graph using the mouse position text as specified coordinates grid lines on
Usually legend command is useful in multiple plot. Continued from above example: >> title(’plot of y = x^2 - 10x + 15’); >> xlabel(’x-axis’); >> ylabel(’y-axis’);
By default figure color is blue. We can insert other color also by typing: >> plot(x,y,’k’);
We can select color, marker type and line style according to our choice as given below.
Color: These are the following colors in MATLAB. Symbol y Color yellow
m magenta
c cyan
r red
g green
b blue
w white
k black
Marker style: The followings are the marker style used in MATLAB. Symbol . o Style point circle Symbol Style triangle triangle down up
∨
∧
x x-mark < triangle left
+ plus > triangle right
* s d star square diamond p h pentagram hexagram
Line style: The followings are the line styles used in MATLAB. Symbol – Style solid
: dotted
–. dash dot
dashed
Multiple Plot The command plot creates linear x-y plots. If x and y are vectors of same length, the command plot(x,y) opens a graphics window and draws an x y plot of the element of x versus the ones of y, e.g.
−
>> x = -4:0.01:4; y = x.^2; plot(x,y); analogously >> s = -10:0.01:10; t = exp(-s.^2); plot(s,t);
By default, the plot command always opens figure(1) and overwrite the old graphics. If a current graphics window (figure) should be kept, another one can be opened with the command figure(2) or simply figure which then becomes the current figure where graphs from subsequent plotting commands will be placed.
>> figure(1);x = -4:0.01:4; y = x.^2; plot(x,y); >> figure(2);s = -10:0.01:10; t = exp(-s.^2); plot(s,t);
Both plots can open in a single figure, that is, the multiple plot can made in a single figure by using the command >> >> >> or >>
x = -2:0.01:2; y = x.^2; s = -10:0.01:10; t = exp(-s.^2); plot(x,y,s,t); plot(x,y); hold on; plot(s,t); hold off;
For plotting specified line types, marker types and colors can be chosen, for example >> plot(x,y,’r--’,s,t,’b:+’);
renders a red dashed line for the first graph and a blue dotted one for the second one where additionally the nodes are marked by the symbol +. Line width of the plotting can be chosen according to our choice, for example >> plot(x,y,’r--’,s,t,’b:’,’LineWidth’,3);
• The conventional plot is a linear plot. The followings are the combination of linear axes with logarithmic axes:
– The semilogx function plots x data on logarithmic axes and y data on linear axes. – The semilogy function plots x data on linear axes and y data on logarithmic axes. – The loglog function plots both x and y data on logarithmic axes.
• Other speciliazed 2-D plotting functions that are worth to be explore via help are polar,
bar, pie, stem, stairs, hist etc. polar(theta,r); stem(x,y); stairs(x,y); hist(x,y); bar(x,y) — For vertical bar plot; barh(x,y)—For horizontal bar plot; pie(x); pie(x,explode) — The operational array explode controls whether or not individual pie slices are seperated from the remainder of the pie. >> >> >> >> >>
x = [10 37 5 6 6]; explode = [0 1 0 0 0]; pie(x,explode); title(’\bfExample of a pie plot’); legend(’One’,’Two’,’Three’,’Four’,’Five’);
• For visualizing 3-D graphics and generating animations: plot3(x,y,z) mesh(x,y,z) surf(x,y,z) surfc(x,y,z) contour(x,y,z) etc. For example
>> x = linspace(-4,4,20); y = x; [X,Y] = meshgrid(x,y); >> Z = exp(-0.5*(X.^2 + Y.^2)); mesh(X,Y,Z);
For mesh, surf, contour plotting create the meshgrid by using the command [X,Y] = meshgrid(xstart:xincrement:xend, ystart:yincrement:yend)
• There are several other plotting functions to produce plots if you are plotting a function:
fplot, ezplot, ezpolar, ezplot3, ezcontour, ezcontourf, ezsurf, ezsurfc etc. For these try to use online help: >> help fplot etc. The inline function is used to introduce the function f in these plots. Let us look the use of inline function to plot ezsurf . >> f = inline(’x*exp(-x^2-y^2)’); >> ezsurf(f, [-pi,pi,-pi,pi])
Here [-pi,pi,-pi,pi] is [xmin,xmax, ymin, ymax].
• inline function: The inline function is a kind of numerical function that is really used in
a short program that operates on numbers to produce numbers. Here is a simple example: >> f = inline(’x^3 + x -1’) f = Inline function: f(x) = x^3 + x -1
To evaluate f (x) = x 3 + x smart, we must write
− 1 at x = 2, enter f (2). If we wish the function to be array
>> f = inline(’x.^3 + x -1’); >> A = [1 2 3;4 5 6]; >> B = f(A) B = 1 67
9 129
29 221
Sublot: The command subplot can be applied to partition the screen so that several small plots can be placed in one figure. Syntax:
subplot(m,n,p)
This command divides the current figure into m n equal sized regions, arranged in m rows and n columns, and creates a set if axes at position p to recieve all plotting commands. The subplots are numbered from left to right end from top to bottom. For example, the command subplot(2,3,4) would divide the current figure into six regions arranged in two rows and three columns, and create an axis in position 4 (the lower left one) to accept new plot data. The following example will display the use of subplot.
×
>> >> >> >> >> >>
figure(1) subplot(2,3,1); x = -pi:pi/20:pi; y = sin(x); plot(x,y); subplot(2,3,5); x = -pi:pi/20:pi; y = cos(x);plot(x,y); title(’Subplot 2 title’);
MATLAB (Exercise - 3) MATLAB Plotting 1. The distance travelled by a ball falling in the air is given by x = x0 + v 0 t + 21 gt 2 .Use Matlab’s plot command to plot t versus x for 0 x 3 when x0 = 10m, v0 = 15m/s 2 and g = 9.81 ms . Write the text ’Ball’ using the command gtext(’Ball’) in the figure window.
≤ ≤
−
2. Plot the functions y(t) = sin t and y(t) = cos t versus time in a single figure window for 2π t 2π where sin t versus time graph is shown by solid red line and cos t versus time graph is shown by blue dashed line with a width of pixels 3. Don’t forget to mention labels, title and legends of the plots.
− ≤ ≤
3. Plot y = e−0.4x sin x, 0 x 4π taking 10, 50 and 100 points in the interval on the same MATLAB figure window.
≤ ≤
4. (a) Plot the function v(t) = 10 e(−0.2+πi)t for 0 What is displayed on the plot?
≤ t ≤ 10 using the function plot(t,v).
(b) Plot the above function using the function plot(v). What is displayed on the plot this time? (c) Plot the real and imaginary parts of v(t) versus time in a single figure window where real versus time graph is shown by solid blue line and imaginary versus time graph is shown by red dashed line. (d) Create a polar plot of the above function. (e) Plot the above function using plot3, where the three dimensions to plot are the real part of the function, the imaginary part of the function and time. 5. Plot the respective 3-D/2-D plots of the following functions:[Take online help] (a) Plot mesh and meshc of the function z = y 3. In the plotting command once use
≤
>> >> >> >> >> >> >> >>
xy(x2 −y 2 ) x2 +y 2
x = -3:.1:3; y = x; [X,Y] = meshgrid(x,y); Z = X.*Y.*(X.^2 - Y.^2)./(X.^2 + Y.^2); figure(1) mesh(X,Y,Z); figure(2) meshc(X,Y,Z);
and secondly Use the plotting command >> >> >> >> >> >> >> >>
−3 ≤ x ≤ 3, −3 ≤
in the range
x = -3:.1:3; y = x; x = x + (x==0)*eps; y = y + (y==0)*eps; [X,Y] = meshgrid(x,y); Z = X.*Y.*(X.^2 - Y.^2)./(X.^2 + Y.^2); figure(1) mesh(X,Y,Z);
>> figure(2) >> meshc(X,Y,Z);
Handle the width of the curves in meshc( ) plot using the command: h = meshc(X,Y,Z) and set(h,’LineWidth’,2). Try to understand the output in the command window and figure window! (b) Plot mesh and meshc of the function z = sin x + sin y in the range 3 x 3, 3 y 3. √ 2 2 x +y − 4 (c) Plot surf and surfc of the function z = cos x cos y e in the range x 5, y 5.
− ≤ ≤
− ≤ ≤
||≤
| | ≤
t
(d) Plot the parametric curve x(t) = t, y(t) = e 2 sin t for 0 < t < π/2 using ezplot. ezplot and fplot command plots the function directly, without the necessity of creating intermediate data array. Plot using fplot command. (e) Plot the function f (x) = sinx between x
−4π and 4π using ezplot and fplot.
(f) Plot the cardiod r(θ) = 1 + cos(θ) for 0 < θ < 2π using ezpolar.
(g) Plot the contours x2 + sin(xy) + y 2 = 0 using ezcontour over the domain x < π/2, π/2 < y < π/2.
−π/2 <
−
(h) Create a surface plot with contours of the function H (x, y) = π < x < π, 2 < y < 2.
−
−
6. Consider the function defined by the equation f (x, y) =
−xye−
x2 −y 2
x2 2
+ (1
− cos y) for
.
(a) Use Matlab’s contour command to plot 20 contours over the domain (x, y) : x, y 2 . Take on line help command .
−2 ≤
{
≤ }
(b) Use the form clabel(c,h,’manual’) to selectively label several contours with the mouse. (c) Use Matlab’s contour3 command to plot twenty contours over the domain (x, y) : 2 x, y 2 . Turn off the grid with the command grid off . Help: Type help contour3 to obtain help on contour3 command.
{
− ≤ ≤ }
(d) Use Matlab’s meshc command to obtain a simultaneous plot of the surface and the level curves of the function over the domain (x, y) : 2 x, y 2 . Remove hidden line with the command hidden off .
{
7. Do the same as in Exercise 6 for the function f (x, y) = the domain (x, y) : 2 x, y 2 .
{
− ≤
− ≤
−3y to x2 +y 2 +1
≤ }
plot 10 contours over
≤ }
8. (Plotting Complex data): Complex data has both real and imaginary components, and plotting complex data with MATLAB is a bit different from plotting real data. For example, consider the function y(t) = e −0.2t(cos t + i sin t) If this function is plotted with the conventional plot command, only the real data will be plotted — the imaginary part will be ignored. In this plot you will get a warning message that the imaginary part of the data is being ignored. Consider the t as t = 0 : pi/20 : 4π. Then (a) Plot the function y(t) using the conventional plot comman plot(t,y) with lineWidth 3. Don’t forget to mention labels and title of the plot.
(b) Plot the real and imaginary parts of y(t) versus time in a single figure where real VS time graph is shown by red-dashed. Mention the respective legends. (c) Plot real VS imaginary parts of y(t). (d) Polar plot for angle of y(t) VS absolute value of y(t). Helpful built-in-functions: real(), imag(), abs(), angle(), hold on 9. Thermodynamics(The ideal gas law): An ideal gas is one in which all collisions between molecules are perfectly elastic. It is possible to think of the molecules in an ideal gas as perfectly hard billiard balls that collide and bounce off of each other without losing kinetic energy. Such a gas can be characterized by three quantities: absolute pressure (P), volume (V) and absolute temperature (T). The relationship among these quantities in an ideal gas is known as the ideal gas low: P V = nRT where P is the pressure of the gas in kilopascals(Kpa), V is the volume of the gas in litres (L), n is the number of molecules of the gas in units of moles(mol), R is the universal gas constant (8.314 L Kpa/mol K), and T is the absolute temperature in kelvins (K ).(Note: 1 mol = 6.023 1023 molecules.)
×
(a) Assume that a sample of an ideal gas contains 1 mole of molecules at a temperature of 273K, and answer the following questions: i. How does the volume of this gas vary as its pressure varies from 1 to 1000 Kpa? Plot pressure versus volume for this gas on an appropriate set of axes (linear, semilog etc?). Use a solid red line with a width of 3 pixels. ii. Suppose that the temperature of the gas is increased to 373 K. How does the volume of this gas vary with pressure now? Plot pressure versus volume for this gas on the same set of axes as part (i). Use a dashed blue line with a width of 2 pixels. (b) Assume that the volulme of 1 mole of this gas is 101, and plot the pressure of the gas as a function of temperature as the temperature changed from 250 to 450 Kelvins. What sort of plot is most appropriate for this data?
0.8
Helpful built-in-functions used in M-files
input function: The input function displays a prompt string in the command window and then waits for the user to type in a response. For example, consider the following statements: my_val = input(’Enter the input value: ’);
If the input function includes the character ’s’ as a second argument, then the input data is returned to the user as a character string. Thus, the statement >> in1 = input(’Enter data: ’); Enter data: 1.34
stores the value 1.34 into in1, while the statement >> in2 = input(’Enter data: ’, ’s’); Enter data: 1.34
stores the character string ’1.34’ into in2.
disp function: The disp function displays the data. The disp function accepts an array argument, and displays the value of the array in the command window. If the array is of type char, then character string contained in the array is printed out. This function is often combined with the functions num2str (converts a number to string) and int2str (converts an integer to string) to create message to be displayed in the command window. For example, the following MATLAB statements >> str = [’The value of pi = ’ num2str(pi)]; >> disp(str);
will display ”The value of pi = 3.1416” in the command window. The first statement creates a string array containing the message, and the second statement displays the message.
fprintf function: An even more flexible way to display data is with the fprintf function. The fprintf function displays one or more values together with related text and lets the programmer control the way the displayed values appear. The general form of this function when it is used to print to the command window is fprintf(format, data)
where format is a string describing the way the data is to be printed, and data is one or more scalars or arrays to be printed. The format is a character string containing text to be printed plus special characters describing the format of the data. For example, the function fprintf(’The value of pi is %f \ n ’ , pi)
Format string Results %d display value as an integer %e display value in exponential format %f display value in floating format %g display value in either floating format or exponential format, whichever is shorter n skip to new line
\
will print out “The value of pi is 3.141593” followed by a line feed. The character %f is a conversion character. It indicates that the value in the data list should be printed out in floating point format at that location in the format string. The character n is an escape character. It indicates that a line feed should be issued so that the following text starts on a new line. Other characters are as shown in table below.
\
fprintf(’The value of pi is %8.2f \ n ’ , pi)
will print out “ The value of pi is 3.14 ” followed by a line feed. The conversion %8.2f indicates that the first data item in the function should be printed out in floating point format in a field eight characters wide, including two digits after the decimal point.
Its limitation: It displays only the real portion of a complex value. >> >> >> >>
x = 2 + 3*i; str = [’disp: x = ’ num2str(x)]; disp(str); fprintf(’fprintf: x = %8.4f \n ’, x);
The results printed out by these statements are disp: x = 2+3i fprintf: x = 2.0000
0.9
M-files
• MATLAB has two M-files. They are script files and function files. • Both are called M-files, because they have a file extension of “ .m”. • Where to type? Select new M-file from the file menu. A new edit window will appear. Type M-files in this window.
Scripts files:
• A script file is a user-created file with a sequence of MATLAB command in it.
It is equivalent to typing all the commands stored in the script file, one by one, at the MATLAB prompt in the command window.
• The file must be saved with a “ .m” extension to its name, thereby, making it an M-file.
The file name must begin with a letter and the rest of the character may include digits and underscores but not period other than the last one “.m”.
• The script file can execute by typing its name (without the “.m” extension)in the command window.
• Script files work on global variables, that is, variables currently present in the workspace. Results obtained from executing script files are left in the workspace.
• Script files are useful when we have to repeat a set of commands several times. • Script files may be used to enter a data into huge matrices, since entry error can be easily corrected.
Example 6 Write a script file to draw a unit circle whose parametric equation is given by x = cos(θ), y = sin (θ), 0
≤ θ ≤ 2π
Solution steps:
• Select New M-file from the file menu. A new edit window will appear. • Type the following lines into this edit window. Lines starting with % sign are interpreted as comment line by MATLAB and are ignored.
% Script file: circle.m % % Purpose: % This program plots the unit circle. % % File written to give idea to students how to creat a script file. % Dated on Feb 14, 2011. % % Define Variables: % theta --- angle in radian. % x --- x = cos(theta). % y --- y = sin(theta). %-------------------------------------------------------------------------% Create array for input variables theta = linspace(0, 2*pi, 100); % creat vector data x = cos(theta); % generates x - coordinates y = sin(theta); % generates y - coordinates % Creates plot plot(x,y); axis(’equal’); title(’Circle of unit radius’); text(0.5,0.5,’note this’);
% % % %
plot the unit circle set equal scale on axes put a title put text at specified point
• Select save as from file menu. A diaglog box will appear. Type the name of the document as circle.m in the folder you want to be. Then click yes to save the file.
• Now to get back to MATLAB type the following in the command window.
>> help circle >> circle
This will display the graph for unit circle. Function files:
• If we want to do a big set of computations but in the end we want only a few outputs, a script file is not the right choice. What we need in this case is a function file.
• A function file is also an M-file, like a script file, except it has a function definition line
on the top that defines the input and output explicitly. The general form of MATLAB function is function [outarg1, outarg2, ...] = fname(inarg1, inarg2, ...)
The followings are the forms of MATLAB function if there is single output or no output. function [output] = fname(inarg1, inarg2, ...) function output = fname(inarg1, inarg2, ...) function [ ] = fname(inarg1, inarg2, ...) function = fname(inarg1, inarg2, ...)
• The function file must be saved in your required folder with the file name fname.m. • The function file can execute by giving the values of the input arguments by typing the format of function file in the command window.
• Function files work on local variables. That is results obtained from executing function files are not left in the workspace.
Example 7 Write a function file to draw a circle of a specified radius, with the radius as the input to the function. Solution steps:
• Select New M-file from the file menu. A new edit window will appear. • Type the following lines into this edit window. Lines starting with % sign are interpreted as comment line by MATLAB and are ignored.
function [x,y] = circlefn(r) % CIRCLEFN --- Draws a circle of a specified radius r. % ------------------------------------------------------------------------% % CALL SYNTAX: [x,y] = circlefn(r); or just circlefn(r); % Input: r = specified radius % Output: [x,y] = the x- and y- coordinates of data points % Dated on Feb 14, 2011. % -------------------------------------------------------------------------theta = linspace(0,2*pi,100); % creat vector data x = r*cos(theta); % generates x - coordinates
y = r*sin(theta); % plot(x,y,’LineWidth’,3); % axis(’equal’); % title([’Circle of radius r = ’, num2str(r)]);% %
generates y - coordinates Plot the circle with 3 pixels set equal scale on axes put the title with the value of r
• Select save as from file menu. A diaglog box will appear. Type the name of the document as circlefn.m in the folder you want to be. Then click yes to save the file.
• Now to get back to MATLAB type the following in the command window. >> help circlefn >> circlefn(3)
This will display the circle of radius 3 having pixels 3.
MATLAB (Exercise - 4) MATLAB Functions 1. Show the center of the circle: Modify the script file circle.m of the example 6 to show the center of the circle on the plot, too. Show the center point with ’red color having marker type +’. 2. Change the radius of the circle: Modify the script file circle.m created above in (1) to draw a circle of arbitrary radius r as follows:
• Include the following command in the script file before the first executable line (theta ...) to ask the user to input (r) on the screen:
r = input(’Enter the radius of the circle: ’)
• Modify the x and y coordinate calculations appropriately. • Save and execute the file. When asked, enter a value for the radius and press return. 3. Temperature Conversion: Celsius (C), Fahrenheit (F), Reaumur (R), Kelvin (K) and Rankine (Ra) are five scales of measurement of temperature. Each scale of temperature has an upper fixed point (boiling point of water) and a lower fixed point (melting point of ice). The difference between these fixed points is called Fundamental units, which is 100 for Celsius, 180 for Fahrenheit, 80 for Reaumur, 100 for Kelvin and 180 for Rankine. The relation between the scale is C 0 F 32 R 0 K 273 Ra 492 = = = = 100 180 80 100 180
−
−
−
−
−
(a) Design a MATLAB program that reads an input temperature in degree Fahrenheit, converts it to an absolute temperature in Kelvin, and write out the result. To do this i. Input the following command to ask user to input the temperature in Fahrenheit in screen: temp_f = input(’Enter the temperature in degree Fahrenheit: ’);
ii. Convert to Kelvins using temp_k = (5/9)*(temp_f - 32) + 273;
iii. Write out the result using fprintf(’%6.2f degree Fahrenheit = %6.2f kelvins \n’,... temp_f, temp_k);
(b) Write a function that outputs a conversion table for Celsius and Fahrenheit temperatures for 1 degree increment in Celsius between two temperatures ti and tf in celsius. For conversion table use the command temp table = [C,F], where C = [ti : t f ]’ and F = (9/5)*C + 32, and output will be named temp table. 4. Statistical Evaluation of data: If all of the input values are available in an array (vector), the mean and standard deviation of a set of numbers can be calculated by MATLAB function mean() and std() respectively. The average mean of a set of numbers N N 2 X i i=1 (X i −X ) is defined by X = i=1 and the standard deviation is defined by σ = . N N Now follow the following steps:
(a) Write a function statistics.m in MATLAB
function [mean, stdev] = statistics(X)
that computes for a given vector X the mean mean and the standard deviation stdev of its components. Note that the input vector X might be a row or column vector of various length. Do not forget the description of the function in the first comment line, remember comment start with %. [Helpful built-in-functions: size(), sum(), sqrt()] (b) Test the function with your following input vectors: y1 = [11 1 3 9 5 7],y2 = [10 6 12 20]’
y3 = vector with random components and arbitrary length n,n > 0. Compare your result with the ones being obtained from the MATLAB built-in-functions mean and std. [Helpful built-in-functions: rand() ] (c)
i. Generate a random input vector y of length n,n > 1000. ii. Call your function statistics.m for the determination of its mean mean and its standard deviation stdev. iii. Visualize the input vector, its mean and standard deviation graphically. Therefore, proceed in the following way: Enter the vector t = [1:n] where n equals the length of y. Plot your input data vector by help of the command plot(t,y,’ko’). Type hold on. Define a vector v of length n whose components are equal to 1. Plot your mean by help of the command plot(t,mean*v,’r-’). Plot your standard deviation around your mean by help of the command plot(t,mean+stdev*v,’b-’) resp. plot(t,mean-stdev*v,’b-.’) Type hold off. [Helpful built-in-functions: rand(), ones()]
• • • • • • •
5. Roots of Quadratic Equations: Write a program that will solve for the roots of a quadratic equation, whether they are distinct real roots, repeated real roots or complex roots, without requiring test on the value of the discriminate. Test the program using real input data from the following quadratic equations. x2 + 5x + 6 = 0 Roots are: -2, -3 x2 + 4x + 4 = 0 Roots are: -2, -2 x2 + 2x + 5 = 0 Roots are: -1+2i, -1-2i
0.10
Branches and Loops
Branches and Loops both are MATLAB construct that permit us to execute a sequence of statements under user control. The syntax for bracnching statements is if-elseif-else and that for control-flow statements are for -loops and while -loops. In addition, MATLAB provides — switch, try/catch, break, error, and return to control the execution of scripts and functions. A description of these functions follows. Branches Branches are MATLAB statements that permit us to select and execute specific selection of code (called blocks) while skipping other section of codes. They are variations of if construct, the switch construct, and the try/catch construct.
The if construct The if construct has the form if control_expr_1 Block 1 statements elseif contro_exp_2 Block 2 statements elseif contro_exp_3 Block 3 statements ...... ................. else Block n statements end
where the control expressions are logical expressions that control the operation of the if construct. Note that there can be any number of elseif clauses in an if construct, but there can be at most one else clause. Nested if Construct The if construct is very flexible. It must have one if statements and one end statement. In between, it can have any number of elseif clauses, and may also have one else clause. With this combination, it is possible to implement any desired branching construct. In addition, if constructs may be nested. Two if constructs are said to be nested if one of them lies entirely within a single code block of the other one. Thus the nested if construct has the form .... if (Test 1) ... if (Test 2) ... if (Test 3)
... end ... end ... end
Example 8 (Assigning letter grades) Suppose that we are writing a program that reads in a numerical grade and assigns a letter grade to it according to the following table: Write an if 95 < 86 < 76 < 66 < 0<
grade grade 95 grade 86 grade 76 grade 66
≤ ≤ ≤ ≤
A B C D F
construct that will assign the grades as described above using (a) multiple elseif clauses and (b) nested if constructs. Solution (a) One possible structure using elseif clauses is: if grade > 95 disp(’The elseif grade > 86 disp(’The elseif grade > 76 disp(’The elseif grade > 66 disp(’The else disp(’The end
grade is A. ’); grade is B. ’); grade is C. ’); grade is D. ’); grade is F. ’);
(b) One possible structure using nested if constructs is: if grade > 95 disp(’The grade is A. ’); else if grade > 86 disp(’The grade is B. ’); else if grade > 76 disp(’The grade is C. ’); else if grade > 66 disp(’The grade is D. ’); else disp(’The grade is F. ’); end
end end end
The switch construct The switch construct is another form of branching construct. It permits a programmer to select a particular code block to execute based on the value of a single integer, character, or logical expression. The general form of switch construct is: switch (switch_expr) case (case_expr_1) Block 1 statements case (case_expr_2) Block 2 statements ........ otherwise Block n statements end
If many values of the switch expr cause the same code to execute, all of those values may be included in a single block by enclosing them in brackets, as shown below. If the switch expression matches any of the case expressions in the list, then the block will be executed. switch (switch_expr) case (case_expr_1, case_expr_2, case_expr_3) Block 1 statements case (case_expr_4, case_expr_5) Block 2 statements ........ otherwise Block n statements end
Example 9 (Integer between 1 and 10 is even or odd:) The following MATLAB program determines whether an integer between 1 and 10 is even or odd, and print out an appropriate message. It illustrates the use of a list of values as case selectors, and also the use of the otherwise block. Solution: % EVEN_ODD --- This script file determines whether an integer between 1 % and 10 is even or odd, and points out an appropriate message. It % illustrates the use of a list of values as case selectors, and also the % of the otherwise block. % ------------------------------------------------------------------------% File name: even_odd.m value = input(’Enter the integer:’); switch value case {1,3,5,7,9} disp(’The integer is odd.’); case {2,4,6,8,10}
disp(’The integer is even.’); otherwise disp{’The integer is out of range.’} end
Loops Loops are MATLAB constructs that permit us to execute a sequence of statements more than once. There are two basic forms of loop constructs: while loops and for loops. The major difference between these two types of loops is in how the repetition is controlled. The code in a while loop is repeated an indefinite number of times until some user-specified condition is satisfied. By contrast, the code in for loop is repeated a specified number of times, and the number of repetitions is known before the loops starts. The while loop A while loop is a block of statements that are repeated indefinitely as long as condition is satisfied. The general form of while loop is: while expression code block end
The controlling expression produces a logical value. If the expression is true, the code block will be executed, and then control will return to the while statement. If the expression is still true, the statements will be executed again. This process will be repeated until the expression becomes false. When control returns to the while statement and the expression is false, the program will execute the first statement after the end.
Example 10 The following MATLAB program which computes the powers of 3 in the interval [10, 200) will show the use of while loop. Solution: % POWER_3--This script file computes the powers of 3 within [10, 200) % File name: power_3.m n = input(’Enter the input value: ’); if (n<=10)|(n>200) disp(’Sorry! The choice is out of range:’); else num = 1; i = 1; c = 0; d = 1; while num < n num = 3^i; c = [c;i]; d = [d;num]; v = [c d]; i = i+1; end end
The for loop The for loop is a loop that executes a block of statements a specified number of times. The for loop has the form for index = expr statement 1 statement 2 ........... statement n end
where index is the loop variable (also known as loop index) and expr is the loop control expression. The columns in expr are stored one at a time in the variable index and then the loop body is executed, so that the loop is executed once for each column in expr. The expression usually takes the form of a vector in shorcut notation first:increment:last . The statements between the for statement and the end statement are known as the body of the loop. They are executed repeatedly during each pass of the for loop.
Usual forms: (a) for i = 1:10 statement 1 ...... statement n end
(b) for i = 1:2:10 statement 1 ......... statement n end
(c) for i = [5 7 9] statement 1 ......... statement n end
(d) for i = [1 2 3;4 5 6] statement 1 ......... statement n end
In (a) the control expression generates a 1 10 array, so statement 1 through n will be executed 10 times. The loop index i will be 1 on the first time, 2 on the second time, and so on. The loop index will be 10 on the last pass through the statements. When control is returned to the for statement after the tenth pass, there are no more columns in the control expression, so execution transfers to the first statement after the end statement. Note that the loop index i is still set to 10 after the loop finishes executing.
×
• Control expression in (b) generates 1 × 5 array. • Control expression in (c) generates 1 × 3 array. • Control expression in (d) generates 2 × 3 array. Example 11 (The factorial function:) The factorial function is defined as n! = 1, n < 0 n! = n(n 1)(n
−
− 2) · ·· 3.2.1, n > 0
The MATLAB code to calculate n factorial for positive value of n would be
n_factorial = 1 for i = 1:n n_factorial = n_factorial*i end
Nested for loop It is possible for one loop to be completely inside another loop. If one loop is completely inside another one, the two loops are called nested loop. The following example shows the two nested for loops used to calculate and write out the product of two integers. for i = 1:3 for j = 1:3 product = i*j; fprintf(’%d*%d = %d\n’, i, j, product); end end
The output is 1*1 1*2 1*3 2*1 2*2 2*3 3*1 3*2 3*3
= = = = = = = = =
1 2 3 2 4 6 3 6 9
Break The command break inside a for or while loop terminates the execution of the loop, even if the condition for execution of the loop is true. An example for break statement in a for loop is shown below: % file name--text_break in script file. for i = 1:6 if i == 3; break; end fprintf(’i = %d\n’,i); end disp([’End of LOOP!’]);
When this program is executed, the output is: >> test_break i = 1 i = 2 End of LOOP!
Continue If a continue statement is executed in the body of a loop, the execution of the current pass through the loop will stop and control will return to the top of the loop. The controlling variable in the for loop will take on its next value, and the loop will be executed again. An example to the continue statement in a for loop in shown below: for i = 1:5 if i == 3 continue; end fprintf(’i = %d \n’,i); end disp([’End of loop!’]);
When this program is executed, the output is: i = i = i = i = End
1 2 4 5 of loop!
Note that the continue statement was executed on the iteration when i was 3, and control transferred to the top of the loop without executing the fprintf statement. The break and continue statements work with both while and for loops.
Nested Break for i = 1:3 for j = 1:3 if j == 3 break; end product = i*j; fprintf(’%d*%d = %d\n’, i, j, product); end fprintf(’End of inner loop \n’); end fprintf(’End of outer loop \n’);
If the inner loop counter j is equal to 3, then the break statement will be executed. This will cause the program to exit the innermost loop. The program will print out End of inner loop, the index of the outer loop will be increased by 1, and execution of the innermost loop will start over. The resulting output values are: 1*1 1*2 End 2*1 2*2
= 1 = 2 of inner loop = 2 = 4
End 3*1 3*2 End End
of inner loop = 3 = 6 of inner loop of outer loop
Error The command error(’message’) inside a function or script aborts the execution, displays the error message message , and returns the control to the keyboard.
MATLAB (Exercise - 5) MATLAB Branches and Loops 1. Examine the following for loops and determine how many times each loop will be executed. a. for i = 7:10 b. for i = 7:-1:10 c. for i = 1:10:10 d. for i = -10:3:-7 2. Examine the following loops and determine the value of res at the end of each of the loops.
3.
a. res = 0; for i = 1:10 res = res +1; end
b. res = 0; for i = 1:10 res = res + i; end
c. res(1) = 0; for i = 1:10 res(i+1) = res(i) + i; end
d. res = 0; for index1 = 1:10 for index2 = index1:10 if index2 ==6 break; end res = res + 1; end end
e. res = 0; for index1 = 1:10 for index2 = index1:10 if index2 == 6 continue; end res = res + 1; end end
• How many times will this loop print ’Hello World’? n = 10; while n > 0 disp(’Hello World’) n = n + 1; end
• How many times will this loop print ’Hello World’? n = 1; while n > 0 disp(’Hello World’) n = n + 1; end
• What values will the following MATLAB code print ? a = 1; while a < 100 a = a*2 end
• What values will the following MATLAB code print ?
a = 1; n = 1; while a < 100 a = a*n n = n + 1 end
• What values will the following MATLAB code print ? a = 4; b = 1; n = 1; while n <= 10 b = b + a^n/factorial(n); n = n + 1; end
4.
• How many times will this program print ’Hello world’ ? for a = 0:50 disp(’Hello World’) end
• How many times will this program print ’Hello world’ ? for a = -1:1:-50 disp(’Hello World’) end
• How many times will this program print ’Hello world’ ? for a = -1:-1:50 disp(’Hello World’) end
• How many times will this program print ’Hello world’ ? for a = 10:10:50 for b = 0:0.1:1 disp(’Hello World’) end end
• What sequence of numbers will the following for loop print ? n = 10; for j = 1:n n = n-1; j end
Explain why this code does and what it does ?
• What does this code do ?
n = 10; for i = 1:n for j = 1:n a(i,j) = 1/(i+j-1); end end
• What value will the following program print ? count = 0; for d = 1:5 for m = 1:4 count = count + 1; end end count
• What value will the following program print ? count = 0; for d = 1:7 for h = 1:24 for m = 1:60 for s = 1:60 count = count + 1; end end end end count
5.
• What will the following MATLAB code print ? a = 10; if a~=0 disp(’a is not equal to 0’) end
• What will the following MATLAB code print ? a = 10; if a > 0 disp(’a is positive’) else disp(’a is negative’) end
• What does this code do ? a = 2; b = 3; if a < b j = -1 end
• What does this code do ? a = 4; b = 3; if a < b j = -1 elseif a > b j = 2; end
• What will the following MATLAB code print ? a = 5; b = 3; c = 2; if a <= b*c disp(’Hello World’) else disp(’Goodbye World’) end
• What will the following MATLAB code print ? a = 5; b = 3; c = 2; if (a < b)*c disp(’Hello World’) else disp(’Goodbye World’) end
• What will the following MATLAB code print ? a = 5; b = 3; if a = b disp(’a and b are equal’) else disp(’a and b are not equal’) end
• For what values of the variable a will the following MATLAB code print ’Hello World’ ?
if a >= 0 && a < 7 disp(’Hello World’) else disp(’Goodbye World’) end
• For what values of the variable a will the following MATLAB code print ’Hello World’ ?
if a < 3 || a > 10 disp(’Hello World’) else disp(’Goodbye World’) end
• For what values of the variable a will the following MATLAB code print ’Hello World’ ?
if a < 8 || a >= 2 disp(’Hello World’) else disp(’Goodbye World’) end
• What does this code do ? for i = 1:10 if (i > j)&( rem(i,2) == 0 ) x(i) = 1; else x(i) = 0; end end
• What does this code do ? n = 10; for i = 1:n for j = 1:n if i==j A(i,j)=2; elseif abs(i-j)==1 A(i,j) = -1; else A(i,j)=0; end end end
6. Do some cool operations: Create a 10 10 random matrix with the command A = rand(10). Now do the following operations:
×
• Multiply all elements by 100 and then round off all elements of the matrix to integers with the commnad A = fix(A).
• Replace all elements of A < 10 with zeros. [Help: [r,c] = find(A < 10) returns the row and column indices i and j of A, in vector r and c, for which Aij < 10]
• Replace all elements of A > 90 with infinity (inf). • Extract all 30 ≤ a ≤ 50 in a vector b, that is, find all element of A that are between ij
30 and 50 and put them in a vector b.
MATLAB (Exercise - 6) MATLAB Programs 1. Write a program for the sum of first n natural numbers. 2. Write a program for the sum of first n odd positive integers. 3. Write a program for the sum of first n even positive integers. 4. Write a program to display an integer is even or odd. 5. Use for loop to perform the calculation of the values of y(k), where y(k) = x = 1.5 and k = 1, 2, , 10.
···
k xn 1 n2 ,
for
6. Write a MATLAB program to evaluate the function y(x) = ln 1−1 x for any user-specified value of x, where x is number x < 1.0. Use an if construct to verify that the value passed to the program is legal. If the value of x is legal, calculate y(x). If not, write a suitable error message and quit. 7. Write a program that allows a user to enter a string containing a day of the week (’sunday’, ’Monday’, ’Tuesday’ etc.) and uses that a switch construct to convert the day to its corresponding number, where Sunday is considered the first day of the week and Saturday is considered the last day of the week. Print out the resulting day number. Also, be sure to handle the case of an illegal day name! (Note: Be sure to use the ’s’ option on function input so that the input is treated as a string) 8. Write an M-file to evaluate the equation y(x) = x 2 3x +2 = 0 for all values of x between -1 and 3 in steps of 0.1. Use a for loop to perform the calculation. Plot the resulting function using a 3-point-thick dahsed red line.
−
9. Write an M-file to calculate the factorial function N !. Be sure to handle the special case of 0!. Also, be sure to report an error if N is negative or not an integer. 10. Fibonacci Numbers: The nth Fibonacci number is defined by following recursive equation: f (1) = 1, f (2) = 2, f (x) = f (x 1) + f (x 2)
−
−
Therefore f (3) = f (2) + f (1) = 2 + 1 = 3, and so forth for higher numbers. Write an M-file to calculate and write out the nth Fibonacci number for n > 2, where n is input by the user. Use a while loop to perform the calculation. 11. Write a function with input parameters x and n that evaluates the nth order Taylor approximation of ex . Write a Script that calls the function for various values of n and plot the error in the approximation. 12. For the up-down sequence xk+1 =
x /2 k
3xk + 1
if x k = even if xk = odd
200 x0 is given. Write a Script that builds up-down sequence while x(k) = 1 and k using the while statement. Plot the solution vector x(k), k = 1, , 200 for several initial conditions.
· ··
≤
Algorithms (Root Findings) 1. Algorithm for Bisection Method Step 1: Choose two approximations a and b (b > a), end points of interval such that f (a) f (b) < 0
∗
Step 2: Evaluate the mid-point c of [a, b] given by a + b 2 Step 3: If f (a) f (c) < 0, then rename a and c by a and b; if not, rename c by a. Step 4: Stop evaluation when the difference of two successive values of c obtained from Step 2 is numerically less than tolerance, the prescribed accuracy. c =
∗
2. Algorithm for Secant Method Step 1: Choose two trial values x1 and x2 such that f (x1 ) f (x2 ) < 0
∗
Step 2: Find the next approximation x3 using x3 = x 2
−
x − x 2
f 2
1
− f
f 2
1
Step 3: Evaluate successive approximations using the recursive formula x(n+1) = x n
−
x − x − n
f n
where f n stands for f (xn ). Step 4: Stop the process, when
n 1
− f −
n = 3, 4, 5,
···
|x − x − | < n
where is the prescribed accuracy.
f n ,
n 1
n 1
3. Algorithm for Regula Falsi Method Step 1: Choose two trial values x1 and x2 such that f (x1 ) f (x2 ) < 0
∗
Step 2: Find the next approximation x3 using x3 = x 2
−
x − x 2
f 2
1
− f
1
f 2
Step 3: If f (x3 ) f (x2 ) < 0, then go to next step. If not, rename x1 and x2 and then go to next step. Step 4: Evaluate successive approximations using the recursive formula
∗
x(n+1) = x n
−
x − x − n
f n
n 1
− f −
n 1
f n ,
n = 3, 4, 5,
···
where f n stands for f (xn). But, before applying the formula for xn+1 , ensure whether f n−1 f n < 0; If not, rename xn−2 as xn−1 and proceed. Step 5: Stop the process, when xn xn−1 <
∗
where is the prescribed accuracy.
| −
|
4. Algorithm for Newton-Raphson Method Step 1: Choose a trial solution x0 . Find f (x0 ) and f (x0 ). Step 2: Next approximation x1 is obtained from x1 = x 0
) − f f (x (x ) 0
0
Step 3: Follow the above procedure to find successive approximations xn+1 using the recursive formula f (xn ) xn+1 = x n , n = 1, 2, 3, f (xn )
−
···
Step 4: Stop when
|x − x − | < n
n 1
where is the prescribed accuracy. 5. Algorithm for Iteration Method Step 1: Express f (x) = 0 as x = φ(x) such that
|φ(x)| < 1 Step 2: Choose a trial function x 0 . Step 3: Find first approximation x1 using x1 = φ(x0 ) Step 4: Follow the above procedure to find successive approximations xn+1 using the recursive formula xn+1 = φ(xn ), n = 0, 1, 2,
· ··
Step 5: Stop when
|x − x − | < n
where is the prescribed accuracy.
n 1
6. Algorithm for Newton Raphsom Method for system of nonlinear equations Step 1: Choose the initial approximate row vector X 0 for the system of equations f (x, y) = 0 and g(x, y) = 0 Step 2: Compute Jacobian J (f, g) at X 0 and F (X 0 ) = [ f (X 0 ) Step 3: Solve the 2 2 nonlinear system of equations
−
×
− g(X )] 0
J (f, g)Y = F (X 0 ) where Y = [h k] Step 4: Improve the iteration by setting X 0 = X 0 + Y Step 5: Stop when norm
X < 0
where is the prescribed accuracy. The norm can be considered euclidean norm or any other norms.