# CE 206: Engineering

Computation Sessional
1.50 Credits, 3hrs/week

Dr. Tanvir Ahmed
Associate Professor

Course Outline
Introduction to hi-level computational programming tools
- MATLAB, Mathematica etc.

Application to numerical analysis
- Basic matrix computations
- Solving system of linear equations
- Solving non-linear equations
- Solving differential Equations
- Interpolation and curve-fitting
- Numerical differentiation
- Numerical integration

Application to engineering problems
- Solving mechanics problems
- Numerical solution of equation of motion etc.

CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed

Introduction to MATLAB

MATLAB (MATrix LABoratory) is a fully-functional
programming language

Original code written by Cleve Moler of UNM in the 1970s, later
released as a commercial package by Mathworks, Inc.

Originally intended for interactive
numerical computations

Interfaces with programs written in
other languages(C++, Fortran)

Widely used in academia, research institutions
and industry worldwide

CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed

MATLAB basics
MATLAB can be thought of as a super-powerful graphing
calculator with many more buttons (i.e. built-in functions)

You can build up your own set of functions suited for a particular
operation

It is an interpreted programming language
-commands are executed line by line

It is capable of graphically representing
computational results simultaneously.
- Not possible in C++, Fortran

CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed

Lecture slides for CE206 .Your CE205 Course references/Lecture slides CE 206: Engg.com Materials in my web space(http://teacher.buet.www.bd/tanvirahmed) .ac. Computation Sessional Dr.mathworks.“Getting Started with MATLAB” Mathworks Inc. You will also need: .Provided with the MATLAB software . Tanvir Ahmed . References and Resources The MATLAB help file documentation .“An introduction to MATLAB” David Griffith .

Print out the codes and figures and keep it in file Mid-term Assessment .Approximately one per week . CE204) . differential equations and numerical methods (CE 205) CE 206: Engg.Individual or group submission Final Quiz Requirements .Solving a problem in a given amount of time Final Project/Assignment . Computation Sessional Dr.Basic familiarity with programming (e.Solving a problem in a given amount of time . Course Layout Class grading .g.Knowledge on linear algebra. Tanvir Ahmed .

–. Computation Sessional Dr.3) e abs() round() ans = 3. MATLAB as a calculator Basic arithmetic operators (+.3)) cos1 ( 0.8  5. Tanvir Ahmed .32) 2 ans = Built-in -0.0488 functions » (3+4i)*(3-4i) (3  4i)(3  4i) ans = sin() asin() 25 cos() acos() » cos(pi/2) cos( / 2) tan() atan() ans = log() log10() 6.5470 CE 206: Engg. /) used in conjunction with brackets ( ) 5 » -5/(4. *.32)^2  (4.1230e-017 exp() sqrt() » exp(acos(0.8+5.

Tanvir Ahmed . Numbers and Formats All computations in MATLAB are done in double precision (15 significant figures) CE 206: Engg. Computation Sessional Dr.

Variables • Variable names and their types do not have to be declared in MATLAB. • If a statement is terminated with a semicolon ( . Computation Sessional Dr. ). y = 5*x. and underscores. Tanvir Ahmed . Example >> x=-13. digits. the results are suppressed • Variable names must start with a letter followed by letters. z = x^2+y y = -65 z = 104 CE 206: Engg. • The name of variable is not accepted if it is reserved word.

2204e-016. smallest value by which two numbers can differ – inf: ∞. Tanvir Ahmed . infinity – NAN or nan: not-a-number CE 206: Engg. – pi: π = 3. Computation Sessional Dr. Variables Commands involving variables – who: lists the names of the defined variables – whos: lists the names and sizes of defined variables – clear: clears all variables – clear name: clears the variable name – clc: clears the command window Avoid using – ans: default variable name for the result.1415926 …… – eps: ε= 2.

4.6. Tanvir Ahmed . Computation Sessional Dr.Entries within a row are separated by spaces or commas.Vector properties using size( ) and length( ) >> a = [1 2 3 4 5 ] >> size(a) a = ans = 1 2 3 4 5 1 5 >> b = [2. -Rows are separated by semicolons.10] b = >> length(a) 2 ans = 4 5 6 8 10 CE 206: Engg. .8. Vectors .

3200 0.b. Computation Sessional Dr.4000 -1. incrementing by the value b until it gets to c >> 3:7 ans = 3 4 5 6 7 >> 0.0000 linspace (a.3:-2 ans = -1.7000 -2. inclusive.1:0.4200 0. Other methods of vector creation The colon operator: generally a : b : c produces a vector of entries starting with the value a. CE 206: Engg.n) generates n equispaced points between a and b.32:0.6 ans = 0.4:-0. Tanvir Ahmed .5200 >> -1.

y) for 0  x  1 Increasing the number of elements in x CE 206: Engg. >> plot(x.1.11). Graphics: plotting functions y  sin 3x >> x = linspace (0. >> y = sin(3*pi*x). Computation Sessional Dr. Tanvir Ahmed .

'g--') >> legend('Sin curve'.cos(3*pi*x). Computation Sessional Dr. ylabel('y axis') >> grid CE 206: Engg.‘b-'.'Cos curve') >> title('Multi-plot ') >> xlabel('x axis'). Tanvir Ahmed . titles. labels.x.y. linestyles and colors >> plot(x.Multiplots.

ylabel('sin 6 pi x') >> subplot(224). Computation Sessional Dr. p) subplot splits the figure window into an mxn array of small axes and makes the pth one active. then the numbering continues across the row CE 206: Engg.Subplot example >> subplot(221). plot(x. plot(x. n.cos(6*pi*x)) >> xlabel('x').ylabel('sin 3 pi x') >> subplot(222).y) >> xlabel('x'). plot(x.ylabel('cos 3 pi x') >> subplot(223).sin(6*pi*x)) >> xlabel('x'). plot(x.cos(3*pi*x)) >> xlabel('x'). Note . Tanvir Ahmed .ylabel('cos 6 pi x') subplot(m.the first subplot is at the top left.

Subplot example CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed .

x = (1+1. changed >> n = 1:100.16).'.71828.. y = x.12) >> xlabel('n').'linewidth'.'markersize'.'.^n.x.Formatted text on plots plot the first 100 terms in the sequence {xn} given by xn = [1 + 1/n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 ≤ x ≤ 1 Default font >> set(0.02:2.8) Markersize changed >> title('x_n = (1+1/n)^n'.'y = e^1 = 2.y.4) superscript >> %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% >> subplot (212) LineWidth >> x = -2:.^2. Tanvir Ahmed ./n).'.exp(1)*[1 1]...*sin(3*pi*x). Computation Sessional Dr.[0 max(n)].^3.2) >> legend('y = x^3sin^2 3\pi x'.'Defaultaxesfontsize'.. changed >> plot(x.. >> subplot (211) >> plot(n. '--'.'fontsize'. ylabel('x_n') Subscript/ >> legend('x_n'.4) Latin >> xlabel('x‘) characters CE 206: Engg.

Tanvir Ahmed .Formatted text on plots plot the first 100 terms in the sequence {xn} given by xn = [1 + 1/n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 ≤ x ≤ 1 CE 206: Engg. Computation Sessional Dr.

Adding additional plots hold on and hold off hold on tells MATLAB to keep the current data plotted and add the results of any further plot commands to the graph. Tanvir Ahmed . CE 206: Engg. » plot(x. Hold off releases the hold on the figure » x = 0:.exp(-x).1:2*pi.'r:*'). » y = sin(x). Computation Sessional Dr. » plot(x.'b') » grid on. » hold on.y.

^x) 10 10 10 9 8 8 10 7 6 6 10 5 4 4 10 3 2 2 10 1 0 0 10 10 0 10 2 4 10 10 6 8 10 10 10 0 1 2 3 4 5 6 7 8 9 10 CE 206: Engg. Tanvir Ahmed .x) semilogy(x. semilogy x = 0:0.^x. semilogx(10.1:10.Other plotting commands: semilogx.1:10. Computation Sessional Dr. 10. x = 0:0.

'-s') grid on 50 10 40 10 30 10 20 10 10 10 0 10 -1 0 1 2 10 10 10 10 CE 206: Engg.2).Other plotting commands: loglog x = logspace(-1.exp(x). Computation Sessional Dr. Tanvir Ahmed . loglog(x.

1) first column CE 206: Engg. Tanvir Ahmed . of data is entered row by row. :) all of rows 1 and 3 A(:. 4 5 6.Matrices A 2-D array. Computation Sessional Dr.1:2) rows 2 through 3 and columns 1 through 2 A([1. or matrix.3]. with spaces (or commas) separating entries within the row and semicolons separating the rows: >> A = [1 2 3. 7 8 9] A = 1 2 3 4 5 6 7 8 9 Extracting bits of matrices: A(j. k’th column A(2:3.k) gives j’th row.

Tanvir Ahmed .3 4] a = 1 2 Use square 3 4 brackets [ ] » cat_a=[a. 5*a. Computation Sessional Dr. 3*a.Numerical Array Concatenation » a=[1 2. 4*a. 6*a] cat_a = 1 2 2 4 3 4 6 8 3 6 4 8 4*a 9 12 12 16 5 10 6 12 15 20 18 24 Use [ ] to combine existing arrays as matrix “elements” CE 206: Engg. 2*a.

n) Returns a m ⅹ n Identity matrix ones(n) Returns a n ⅹ n matrix of ones ones(m.n) Returns a m ⅹ n matrix of ones For a m ⅹ n matrix A.More on Matrices zeros(n) Returns a n ⅹ n matrix of zeros zeros(m. returns the row size(A) vector [m.n] containing the number of rows and columns in matrix Returns the larger of the number of rows or length(A) columns in A CE 206: Engg.n) Returns a m ⅹ n matrix of random numbers eye(m.n) Returns a m ⅹ n matrix of zeros rand(m. Computation Sessional Dr. Tanvir Ahmed .

If A is a matrix.Diagonal Matrix First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix >> d = [-3 4 2]. D = diag(d) d = -3 4 2 D = -3 0 0 0 4 0 0 0 2 This command is useful when we need to construct very large matrices. Computation Sessional Dr. diag(A) extracts the diagonal elements of the matrix. Tanvir Ahmed . CE 206: Engg.

v) S = (1.2) 10 Creating a 5-by-4 sparse matrix S having (3.4].3) = 11 and 0 10 0 0 S(5.2) = 10. j = [2. >> v = [10 11 12].4) = 12 0 0 0 0 0 0 11 0 0 0 0 0 The “full” command displays the sparse 0 0 0 12 matrix CE 206: Engg. Tanvir Ahmed .Sparse Matrix These are generally large matrices that have a very small proportion of non-zero entries >> i = [1. 5]. 3.3) 11 only 3 non-zero values: (5.j. >> T = full(S) T = S(3. >> S = sparse (i.4) 12 S(1. Computation Sessional Dr.3.

Matrix operations Transpose B = A’ Addition and C = A+B C = A-B Subtraction Scalar B = αA. A must be a square matrix Operators * ^ and / have two modes of operation -standard -element-wise CE 206: Engg. A must be a square matrix Matrix powers B = A * A . where α is a scalar Multiplication Matrix C = A * B Multiplication Matrix Inverse B = inv(A). Tanvir Ahmed . Computation Sessional Dr. A must be a square matrix Determinant det(A).

Computation Sessional Dr. Tanvir Ahmed .Standard matrix product operation CE 206: Engg.

/. BOTH dimensions must match (unless one is scalar) CE 206: Engg. Computation Sessional Dr. . Tanvir Ahmed .*.^).Elementwise matrix operations To do element-wise operations. .(. use the dot .

4. F(1:19). >> for i = 3:20 F(i) = F(i-1) + F(i-2). Computation Sessional Dr. F(1:19).'o' ) >> hold on. end >> plot(1:19./F(2:20)./F(2:20).'--') CE 206: Engg. F(2) = 1. xlabel('n') >> plot(1:19.e.'-' ) >> legend('Ratio of terms f_{n-1}/f_n') >> plot([0 20].. fn/fn-1 = (√5-1)/2 where n = 3. i.for loop Used when we want to repeat a segment of the code several times Example: Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (√5-1)/2 . (sqrt(5)-1)/2*[1.5 …. Tanvir Ahmed . >> F(1) = 0.1].

Computation Sessional Dr. The while loop is used when we do not know for certain how many iterations may be needed Example: What is the greatest value of n that can be used in the sum and get a value less than 100? >> S = 1. end >> [n. >> while S+ (n+1)^2 < 100 n = n+1.while loop when we want to repeat a segment of the code several times until some logical condition is satisfied. n = 1. Tanvir Ahmed . S = S + n^2. S] ans = 6 91 CE 206: Engg.

0000 -5.0000 > Greater than >> x > 3 & x < 4 < Less than ans = 0 1 0 >= Greater or equal 0 0 0 >> x > 3 | x == -3 <= Less or equal ans = & && And 0 1 1 0 1 0 | || Or Matlab represents true and false by means of the integers 0 and 1 CE 206: Engg. Tanvir Ahmed .Logical and relational operators == Equal x = ~= Not equal -2.0000 -3.0000 3.1416 5. Computation Sessional Dr.0000 -1.

100)). Computation Sessional Dr.10*pi. how many count=count+1. Tanvir Ahmed . for n=1:length(x) Example: Given if x(n)>0 x= sin(linspace(0.Flow control using if/else/elseif count=0. of the entries are positive? end end CE 206: Engg.

2 Columns 13 through 15 0 37 38 39 -0. 1 >> k = find(y > 0. >> y = sin(3*pi*x).2) 0.4 -0.8 >> plot(x(k). -0.y.6 -0.2 -0.8 1 CE 206: Engg.4 -0. Tanvir Ahmed .^2).2 >> x = -1:.':').2 0.6 >> plot(x.y(k). hold on.*exp(-x. Example: Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 0. Computation Sessional Dr.6 9 10 11 12 13 22 23 0.6 0.4 24 25 26 27 36 0.2 0 0.8 -0.The find command for vectors returns a list of the positions (indices) of the elements of a vector satisfying a given condition.'o‘) -1 -1 -0.8 k = Columns 1 through 12 0.4 0.05:1.

+1002 sum_sq=0. end Vectorization CE 206: Engg. how many of the entries are positive? Using the “find” command count=0. Tanvir Ahmed . Computation Sessional Dr. end end Example 2 find the sum: 12 + 22 + 32 + ……………. for n=1:100 Sum_sq=sum((1:100). for n=1:length(x) if x(n)>0 Count=length(find(x>0)).100)).Avoiding loops: efficient coding Example 1: Given x= sin(linspace(0.^2) sum_sq = sum_sq + n^2.10*pi. count=count+1.

g. Tanvir Ahmed . for n=1:length(x) if x(n)>0 count=count+1. Computation Sessional Dr.Avoiding loops: efficient coding Built-in functions (e. sum) will make it faster to write and execute count=0. end end Vectorized code is more efficient for MATLAB Use indexing and matrix operations to avoid loops CE 206: Engg. find.

^2.y) at all the gridpoints -Use a surface plot feature (e. 0. mesh. y) gridpoints at certain intervals . 1:.g. Z = (X-3). 1 mesh(X.surf) to plot the surface Example: Plot the surface defined by z = (x . Advanced graphics: plotting surfaces .3)2 + (y – 2)2 for 2≤ x ≤ 4 amd 1 ≤ y ≤ 3 Saddle [X.5 xlabel('x'). Computation Sessional Dr.5 2.The command meshgrid is used to construct the (x.5 3 1.5 y 1 2 x CE 206: Engg.2:4.5 -1 3 2.^2-(Y-2).Z) title('Saddle').Y. Tanvir Ahmed .Y] = meshgrid(2:.2:3).Evaluate the function z = f(x.5 4 2 3.ylabel('y') 0 -0.

Z) 0.5 0. Advanced graphics: surf and shading Saddle [X.5 1.5 2.5 4 2 3. Z = (X-3).5 -0.5 3.5 title('Saddle‘) shading faceted 0 -0.2:3).5 2 3 3 1.5 3 colormap(gray) y 1.5 4 2. 1:.5 1 2 2.Y] = meshgrid(2:.^2-(Y-2).5 -1 -1 3 3 2.5 0 0 -0. 1 surf(X.^2.Y.5 2.5 y 1 2 1 2 x y x CE 206: Engg. Computation Sessional Dr.5 4 2 3.2:4. Tanvir Ahmed .5 shading flat -1 3 2.5 x Saddle Saddle 1 1 0.

Y. 2 y=-pi:0.'LineWidth'.5 mesh(X.π ≤ y ≤ π 3 x=-pi:0. -1 4 contour(X.Z) 2 4 0 2 0 -2 -2 -4 -4 CE 206: Engg.2) -1 -2 1 -3 -3 -2 -1 0 1 2 3 0.Y]=meshgrid(x. 1 [X.Z). Advanced graphics: contour plot Takes the same arguments as surf or mesh Example: Plot the contour of the surface defined by z = (sinx) (cosy) for –π ≤ x ≤ π and .Z. hold on.y). Tanvir Ahmed .1:pi. 0 contour(X.1:pi.*cos(Y).5 0 -0. Z =sin(X). Computation Sessional Dr.Y.Y.

Specialized plotting functions polar-to make polar plots polar(0:0.rand(1.rand(1.cos((0:0.rand(10)).Y.01:2*pi)*2)) bar-to make bar graphs bar(1:10.1:10).01:2*pi.[0 0 1].10)). Computation Sessional Dr.Y]=meshgrid(1:10.'r'). stairs-plot piecewise constant functions stairs(1:10.5]. fill-draws and fills a polygon with specified vertices fill([0 1 0. Tanvir Ahmed . quiver(X. quiver-to add velocity vectors to a plot [X. CE 206: Engg.rand(10).10)).

m extension CE 206: Engg. Commonly known as m-files because they have a . Tanvir Ahmed . Scripting Script files are ASCII (text) files containing MATLAB commands. Computation Sessional Dr.

Also the name of the m-file List of output(s) where the function definition will be stored.b. Tanvir Ahmed .c: Lengths of sides to aid the future % Output: users % A: area of triangle s = (a+b+c)/2. Computation Sessional Dr. List of inputs function [A] = area(a. function and how it % Inputs: can be used.c) % Compute the area of a triangle whose Purpose of the % sides have length a. The code %%%%%%%%% end of area %%%%%%%%%%% CE 206: Engg. Function m-files Example: Write a function m-file which calculates the area of a triangle having sides a. A = sqrt(s*(s-a)*(s-b)*(s-c)).b. b and c using the formula: Area = s(s  a)(s  b)(s  c) Where s = (a+b+c)/2 The function name. b and c. Mainly % a.

inputs end CE 206: Engg. built in figure function if nargin == 1 nargin plot(x.f1*16+1). Computation Sessional Dr. contains the elseif nargin == 2 number of disp('Two inputs were given'). 2π]. uses f1 as the input but displays a message when two inputs are given function plotSin(f1. Function overloading MATLAB functions are generally overloaded 􀂾 Can take a variable number of inputs 􀂾 Can return a variable number of outputs You can overload your own functions by having variable input and output arguments The following function plots a sine wave with frequency f1 on the range [0.f2) x=linspace(0. Tanvir Ahmed .sin(f1*x)).2*pi.