MATLAB NUMERICAL METHOD LAB MANUAL, Lab Reports of Numerical Methods in Engineering

This lab manual deals with MATLAB covering mainly all the methods being taught in numerical methods...it contains all the codes that are needed to run those methods on MATLAB...it is for beginners because this document tells you to learn MATLAB from scratch..it is helpful for both teachers and students.

Typology: Lab Reports

2021/2022

Available from 08/16/2022

SamenKhan
SamenKhan 🇵🇰

231 documents

1 / 57

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
Numerical Methods
LIST OF EXPERIMENTS
EXPERIMENT 1 FUNDAMENTAL CONCEPTS ............................................................................................ 2
EXPERIMENT 2 ERROR ANALYSIS & JACOBI METHOD ....................................................................... 12
EXPERIMENT 3 BISECTION, FALSE POSITION AND SECANT METHOD............................................ 19
EXPERIMENT 4 NEWTON AND FIXED POINT METHODS ..................................................................... 27
EXPERIMENT 5 LAGRANGE INTERPOLATION ....................................................................................... 32
EXPERIMENT 6 NEWTON INTERPOLATION ............................................................................................ 37
EXPERIMENT 7 LEAST SQUARE METHOD ............................................................................................... 41
EXPERIMENT 8 OPERATORS ....................................................................................................................... 43
EXPERIMENT 9 NUMERICAL DIFFERENTIALS ....................................................................................... 45
EXPERIMENT 10 FINITE DIFFERENCES .................................................................................................... 47
EXPERIMENT 11 NUMERICAL INTEGRATION (Simpson Rule) .............................................................. 49
EXPERIMENT 12 NUMERICAL INTEGRATION (trapezoidal Rule) .......................................................... 51
EXPERIMENT 13 EULER’S METHOD .......................................................................................................... 53
EXPERIMENT 14 RUNGA KUTTA METHOD ............................................................................................. 55
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39

Partial preview of the text

Download MATLAB NUMERICAL METHOD LAB MANUAL and more Lab Reports Numerical Methods in Engineering in PDF only on Docsity!

1 Numerical Methods

  • EXPERIMENT 1 – FUNDAMENTAL CONCEPTS LIST OF EXPERIMENTS
  • EXPERIMENT 2 – ERROR ANALYSIS & JACOBI METHOD
  • EXPERIMENT 3 EXPERIMENT 4 – – BISECTION, FALSE POSITION AND SECANT METHODNEWTON AND FIXED POINT METHODS
  • EXPERIMENT 5 – LAGRANGE INTERPOLATION
  • EXPERIMENT 6 – NEWTON INTERPOLATION
  • EXPERIMENT 7 – LEAST SQUARE METHOD
  • EXPERIMENT 8 EXPERIMENT 9 – – OPERATORSNUMERICAL DIFFERENTIALS
  • EXPERIMENT 10 – FINITE DIFFERENCES
  • EXPERIMENT 11 – NUMERICAL INTEGRATION (Simpson Rule)
  • EXPERIMENT 12 – NUMERICAL INTEGRATION (trapezoidal Rule)
  • EXPERIMENT 13 EXPERIMENT 14 – – EULER’S METHODRUNGA KUTTA METHOD

2 Numerical Methods – Fundamental Concepts

EXPERIMENT 1 – FUNDAMENTAL CONCEPTS

Objective

  • Introduction of MATLAB
  • Understand how programs are written in MATLAB
  • U declaration and Rules for variablesnderstand the MATLAB windows, working with basic commands, Elementary built in functions, Variable Time Required : 3 hrs Programming Language : MATLAB Software Required : MATLAB/ available online (https://octave-online.net/) Hardware Required : NIL Introduction MATLAB is stand for MATrix LABoratory. It is a mathematical package based on matrices and consists of extensive library of numerical routines.
  • All Data stored in the form of a matrix
  • Case-sensitive
  • The basic data type is matrix (normally with 16 decimals precision)
  • Possible to handle complex numbers
  • High-Level programming language and Matrix based computing environment
  • Visualization of data as advanced graphics two and three dimensional How to run MATLAB From Start Menu - > Select Programs - >Select MATLAB 7.

Working with command window

  • Type command in the front of command prompt (>>)
  • Press Enter key, the command is executed.
  • Several commands can be typed in the same line by separating by comma.
  • Previously typed command can be recalled by up-arrow key and down-arrow key can be used to move down the previously typed commands.
  • If the command is too long to fit in one line, it can be continued to the next line by typing three dots … (called an ellipsis)

MATLAB Prompt Tells that MATLAB is ready for your command

4 Numerical Methods – Fundamental Concepts

Predefined Variables A number of frequently used variable are already defined when MATLAB is started. Some are listed here. Ans A variable that has the value of the last expression that was not assigned to a specific variable. pi eps TheThe smallest number π (3.1416) difference between two number Equal to 2^ (-52), which is appx 2.2204e- 016 inf Used for infinity i Defined as ( - 1) ^ (1/2), which is 0+1.0000i j Same as i. NaN Stands for Not a Number. Used when MATLAB cannot determine a valid numeric value. (0/0)

Creating Matrix/Arrays The Matrix/Array is a fundamental form that MATLAB uses to store and manipulate data. It is a list of numbers arranged in rows and/or columns. Simplest way to create matrix is to use the constructor operator [ ]. One Dimensional It is a list of numbers that is placed in a row or a column. Variable_name=[ type vector elements ] Row Vector: To create a row vector type the element with a space or a comma between the elements inside square brackets. row = [E 1 , E 2 , … Em] or row = [E 1 E 2 … Em]

A Column Vector: = [12, 62, 93, To create a - 8, 22] column vector type the element with a semicolon between the element or press the enter key after each element inside square brackets. col = [E1; E2; … Em] or row = [E 1 E 2 B= [12; 62; 93; - 8; 22]^ …^ Em] Example Date Year 2007 2008 2009 2010 Population (Millions

Practice A trigonometric identity is given by 2 : Trigonometric identity Variable that the identity is correct by calculating each side of the equation, substituting x=π/5^ cos^2 (x/2) = (tan x +sin x)/2tax x

x=pi/5; LHS=cos(x/2)^2 LHS = 0. RHS = 0.9045 RHS=(tan(x)+sin(x)) /(2*tan(x))

Practice 3 >> yr= [2007 2008 2009 2010] %Year is assigned to a row vector named yr. yr = 2007 2008 2009 2010

pop= [136; 158; 178; 211] pop = %Population data is assigned to column vector named pop. (^136158) (^178211)

5 Numerical Methods – Fundamental Concepts

Matrix creation using: Operator (colon) Colon operator is used to create a vector with constant spacing the difference between the elements is the same. Where start is first term, stop is last term and step is spacing between elements. The default value of step is 1.^ Variable_name= [^ start:^ step:^ stop ]^ or^ start:^ step:^ stop

Note: If stop value can not be obtained by add step’s to stop then the last element is the vector with be last number that does not exceed stop. Matrix creation using linspace function The linspace function is used to generate a row vector of n linearly equally spaced elements. Where start is first element, stop is last element and n is the total number of elements are created. The default^ Variable_name=linspace( start, stop, n ) value of n is 100.

Two Dimensional A two dimensional array/matrix has numbers in rows and columns. Matrix can be used to store information like in a table. Variable_name= [ 1 st^ row elements; 2nd^ row elements; …….; last row elements ] To create a matrix, type the element with a semicolon between the rows or press the enter key after each row inside square brackets. row = [RE1; RE2; … REm] or row = [RE 1 RE 2 … REm]

Practice >> x=linspace (0,1); (^5) %100 equally spaced elements are created

8 va=linspace (0,8,6) %6 elements, first element 0, last element va = >> vb=linspace 0 1.6000 (30,10,11); 3.2000 4.8000 6.4000 8. vc=linspace (49.5,0.5); %100 elements will be displayed

Practice >> a= [5 35 43; 4 76 81; 21 32 40] (^6) %A semicolon is typed before a new line

b= [ 7 2 76 33 8 1 98 6 25 6 %Press enter before a new row 5 54 68 9 0] cd=6; e=3; h=4; >> Mat=[e,cdh,cos(pi/3);h^2,sqrt(hh/cd),14] %Three variable are defined Mat = 3.0000 (^) 24.0000 0.5000 %Elements are defined by expressions 16.0000 1.6330 14.

Practice 4 >> yr= [2007: 2010] %Year is assigned to a row vector named yr. yr = 2007 2008 2009 2010

x= [1: 2: 13] x = 1 3 5 7 9 11 13 %First element is 1, spacing 2 and last 13 y= [1.5: 0.1: 2.1] y = 1.5000 1.6000 1.7000 1.8000 1.9000 2.0000 2.10 00 x = - pi/2:2*pi/60: pi/2;

7 Numerical Methods – Fundamental Concepts

Graphics MATLAB produce two and three dimensional plots of curves and surface Two Dimensional Plots

  • Plots are very useful tool for presenting information.
  • Plot title, Legend, X axis label, Y axis label, Text label and Markers.
  • Graph is shown in figure window. Plot Command The plot command is used to create two dim plots. The simplest form of the command is plot (x, y), Where x (horizontal axis) and y (vertical axis) are vector. Both vectors must have the same number of elements. The curve is constructed of straight line segments that connect the points. The figure that is created has axes with linear scale and default range. Line Specifiers:
  • Line specifiers are optional and can be used to define the style and coloar of the line and the type of markers.
  • Within the string the specifiers can be typed in any order.
  • Specifier is optional i.e. None, one, two, or all the three can be included in command. Line Style Specifier Line Color Specifier Marker Type Specifier solid(default) - red r plus sign + dashed -- green g circle o dotted : blue b asterisk * dash-dot -. cyan c point. magenta m square s yellow y diamond d black k white w

Plot of function Plot of given function can be done in MATLAB by using the plot or the fplot commands. Using plot: domain that function will be plotted. Plot a function y=f(x) with plot command, user first needs to create a vector of values of x for the Then a vector y is created with the corresponding values of f(x) by using element by element calculation Plot the x and y vectors by using plot command. Using fplot: Plot a function y=f(x) with fplot command between specified limits. fplot(‘function’, limits, n, line specifiers) function can be typed directly as a string and The function cannot include previously defined variables.

Practice >> x=[-2:0.01:4 1 0 Plot y= ]; sin(x) on interval - 2 and 4

y >>plot(x,y=sin(x),’r’;) plot(x,y,’r’); >>plot(x,y,’--y’); plot(x,y,’*’); >>plot(x,y,’g:d’);

8 Numerical Methods – Fundamental Concepts

limits is a vector with two element that specify the domain of x [xmin,xmax] or [xmin ,xmax,ymin,ymax]. n is the number of points between interval. Line specifier are the same as in plot command. Using the hold on, hold off commands Hold on command keeps the figure window with first plot open, including the axis properties and formatting if any was done. Additional graphs can be added with plot command that is typed next. Hold off command stops this process. The grid command grid on %adds grid lines to the plot grid off %removes grid lines from the plot

M-Files

  • Files that contain a MATLAB code are called the m-files. There are two kinds of m-files: 1. script files Script files is a sequence of MATLAB statements and do not take the input arguments or return the output arguments 2. function files The function files may take input arguments or return output arguments. Function name should be same as the name of the file without .m extension
  • To make the m-file click on File next select New and click on M-File
  • To open the m-file from within the Command Window type >>edit filename Script Files
  • A Script file is a sequence of MATLAB command also call a program.
  • When a script file runs, MATLAB executes the commands in the order they are written.
  • When a script file displayed the output in command window.
  • It is convenient way to edit and execute command many times.
  • Script file can be typed and edited in any text editor and saved as .m file.
  • Script files is also called M-files because the extension .m is used. The input command The input command is used to prmpt user to assign a value to variable in command window. The string is a^ variable_name= message prompting the user to enter a value that is assigned to variable.input (‘string with a message that displayed in command windows’) The disp command The input command is used to display the elements of a variable and to display text. Every time the disp command is executed, the display it at new line.^ disp^ (name of the variable)^ or^ disp^ (‘text as string’)

Practice Examples: (^11) y=cos(x), z=cos(x)2 for 0<=x<=pi %Two or more graphs can be created in the same plot by typing pairs of vectros. >>x=0:0.1: pi; % specifies the domain

y=cos(x); >>z=cos(x). ^2; %% define 2 define 1stnd^ function (^) function plot(x,y,x,z,’o’) % display graph. (x, y 1st^ fun, x, y 2nd^ fun) fplot(‘ >>hold oncos’,[-2, 4 ]) fplot(‘sin’,[-2, 4 ])

10 Numerical Methods – Fundamental Concepts

Defines the name of function Defines the number and order of the input and ouput arguments. function [output arguments]=function_name(input arguments)

The feval command evaluates the value of a function for given value of arguments. feval Command Variable=feva(‘function name’, arguments value) The function name typed as string The function can be a built in or user defined function More then one arguments are separated by commas. More then one output are stored in matrix ([a,b,c,.... .])

Summary: In this lab practical students understand the programming concepts of for every student for implementation and analysis of Numerical Method. MATLAB. These concepts are essential

EXERCISES

Exercise 1. Use sum for MATLAB to show that the sum of the infinite series sum(1/n2) converges to pi2/6. Do it by computing the n= n= n= n=

Practice >>feval(‘sqrt’,64) 15 ans=8 >>feval(‘FtoC’,70);

[M,T]=feval(‘loan’,50000,3.9,10) M=502. T=60266.

Practice Function C = FtoC(F) 14 FtoC.m %FtoC converts degrees F to degrees C C=5*(F-32)./9;

FC=inline(‘5(F >>z=FC(70); -32)./9’); %f(x,y)=2x >>HA=inline(‘2x^2^2 - 4xy+y^2 - 4xy+y^2’); z=HA(2,3) z=- 7

11 Numerical Methods – Fundamental Concepts

Exercise 1. 2 Create a 6 x6 matrix in which the middle two rows and the middle two columns are 1’s and the rest are 0’s Exercise 1. Using the eye command create the array A of order 7 x 7. Then using the colon to address the elements in the array change the array as show bellow 2 2 2 0 5 5 5 2 2 2 0 5 5 5 3 3 3 0 5 5 5 A= 0 0 0 1 0 0 0 4 4 7 0 9 9 9 4 4 7 0 9 9 9 4 4 7 0 9 9 9 Exercise 1. 4 Create a vector, name it Afirst, that has 16 equally spaced elements. First element is 4 and last element is 49. Create a new vector, call it Asecond that has eight elements. The first four elements are the first four elements of the vector Afirst, and the last four are the last four elements of the vector Afirst. Exercise 1. 5 Write a function that should take a number as input and calculate factorial of each and every number starting from 0 to given input number. Input should be a fixed number and outputs should be an array of factorials.

Exercise 1. 6 Write a script file that should plot the function 3e2πft whose sampling period should be 0.001 and frequency should be 2. Color of final plot should be red and add legends; labels to the plot, line should be thick.

13 Numerical Methods – Error Analysis & Jacobi Method

Example To infer the surface shape of an object from images taken of a surface from three different directions, one needs to solve the following set of equations.

3

2

1 x

x

x

The right hand side values are the light intensities from the middle of the images, while the coefficient matrix is dependent on the light source directions with respect to the camera. The unknowns are the incident intensities that will determine the shape of the object.

Find the values of x 1 , x 2 , and x 3 using the Gauss-Seidel and Jacobi method. Use

3

2

1 x

x

x

as the initial guess and conduct two iterations. Solution (Gauss Rewriting the equations gives - Seidel)

  1. 2425 x 1 =^247 −^0 x^2 −−^0.^9701^ x^3
  1. 2425 x 2 =^248 −^0 x^1 −−^0.^9701^ x^3
  1. 9428 3 239 0.^235710.^23572 − x = − − x −− x

Iteration # Given the initial guess of the solution vector as

3

2

1 x

x

x

we get ( )

x 1 =^247 −^0 ^10 − −0.9701^ ^10 = 1058. 6

14 Numerical Methods – Error Analysis & Jacobi Method

( )

  1. 2425 x 2 =^248 −^0 ^1058.^6 − −^0.^9701 ^10 =^1062.^7 ( ) ( )
  2. 9428 3 239 0.^23571058.^60.^23571062.^7 − x = − −  − −  =− 783. 81

The absolute relative approximate error for each xi then is

 a 1 =^10581058.^6 .− 610  100 = 99. 055 %

 a 2 =^10621062.^7 .− 710  100 = 99. 059 %

 a 3 =−^783 − 783.^81. 81 −^10  100 = 101. 28 %

At the end of the first iteration, the estimate of the solution vector is

3

2

1 x

x

x

and the maximum absolute relative approximate error is 101. 28 %.

Iteration # The estimate of the solution vector at the end of Iteration #1 is

3

2

1 x

x

x

Now we get ( ) ( )

  1. 2425 x 1 =^247 −^0 ^1062.^685 − −^0.^9701 ^ −^783.^8116 =− 2117. 0 ( ) ( ) ( )
  2. 2425 x 2 =^248 −^0  −^2117.^0 − −^0.^9701 ^ −^783.^81 =− 2112. 9 ( ) ( ) ( ) ( )
  3. 9428 3 239 0.^23572117.^00.^23572112.^9 − x = − −  − −− −

16 Numerical Methods – Error Analysis & Jacobi Method

Practice 1 Estimation of Initial Points The initial value P=[0;0;0] when the matrix M is strictly dominant diagonal. |Aii|>|Bij| & |Aii|>|Cij| Implementation with no of iteration and error significance function X = fjacobi(A,B,P) % X = fjacobi(A,B,P) % A is an nxn diagonally dominant matrix, input. % B is a nx1 vector, input. % P is an nX1 starting vector, input. d = diag(A); D = diag(d); X = D(B - (A-D)*P);

**Implementation of Jacobi Method

M = [5 - 2 3;-3 9 1; 2 - 1 - 7]** M = 5 - 2 3

  • 3 9 1 2 - 1 - 7 >> b=[1;2;3] b = 1 2 3 >> invD = diag( M ).^- 1 invD =

>> Moff = M - diag( diag( M ) ) Moff = 0 - 2 3

  • 23 - (^01 )

>> x = [0;0;0] % initial Values x = 0 0 0

for i=1:

17 Numerical Methods – Error Analysis & Jacobi Method

Gauss a=[9 - Seidel Method 1 1;2 10 3;3 4 11] b=[10 19 0] d=diag(a); k=10; x=[1 1 1]; p=[]; for i=1:k x(1)=(b(1) x(2)=(b(2)--a(1,2)x(2)a(2,1)x(1)--a(1,3)x(3))/d(1);a(2,3)x(3))/d(2); x(3)=(b(3) p=[p;x]; -a(3,1)x(1)-a(3,2)x(2))/d(3); end p

xnew = invD .* (b - Moff*x); if ( abs ( x - xnew ) < 1e-5 ) break; end x = xnew; end >> i i = 10 % number of iterations

>> format long

>> M \ b % the exact solution ans =

>> xnew xnew = % our approximate solution

Gauss-Seidel Method

Summary: In this lab practical students understand implementation concepts of Jacobi Methods. Further they will be able to write a script and function for Jacobi Methods. They also understand the error analysis techniques.

EXERCISES

Exercise 2.1: [ 3 ]

19 Numerical Methods – Bisection, False Position and Secant Method

EXPERIMENT 3 – BISECTION METHOD

Objective

  • Understand the implementation of bisection methods Time Required Programming Language :: 3 hrsMATLAB Software Required : MATLAB Hardware Required : NIL Algorithm Flow Chart

20 Numerical Methods – Bisection, False Position and Secant Method

Where f is the function for which root is required. a and b are initial roots interval and delta is convergence value. Formula used for maximum number of iterations is max1=1+round((log(b-a)-log(delta))/log(2)); Example To find the inverse of a value a , one can use the equation

f ( c )= a −^1 c = 0

where c is the inverse of a.

Use the bisection method of finding roots of equations to find the inverse of a = 2. 5. Conduct three iterations to

estimate the root of the above equation. Find the absolute relative approximate error at the end of each iteration and the number of significant digits at least correct at the end of each iteration.

%% function Program [k,c,err,yc]=bisect(f,a,b,delta) Bisect.m %Input right endpoints- f is the fun - delta is the tolerance - a and b are the left and %Output estimate - forc is c the zero - yc= f(c) - err is the error ya=feval(f,a); if yayb>=0 yb=feval(f,b); c=(a+b)/2; err=abs(b-a); yc=feval(f,c); fprintf( return 'The root is not lying in interval') end max1=1+round((log(b-a)-log(delta))/log(2)) fprintf( fprintf(''k\t\tt\ttLeft endpoint\t\t\t\tt\tt \tMidpoint\tRight\tt\tFunt\tendpoint Value\n'\t)\tf(c)\n') for k=1:max1 c=(a+b)/2; yc=feval(f,c); fprintf( if yc==0'%d \t %15.8f\t%15.8f\t%15.8f\t%15.8f\n',k,a,c,b,yc); elseif^ a=c; ybyc>0^ b=c; else^ b=c;^ yb=yc; end^ a=c;^ ya=yc; end^ if^ b-a^ <^ delta,^ break,^ end c=(a+b)/2; err=abs(b-a); yc=feval(f,c);