

















































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
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
1 / 57
This page cannot be seen from the preview
Don't miss anything!


















































2 Numerical Methods – Fundamental Concepts
Objective
Working with command window
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
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
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
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.
3
2
1 x
x
x
as the initial guess and conduct two iterations. Solution (Gauss Rewriting the equations gives - Seidel)
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
( )
At the end of the first iteration, the estimate of the solution vector is
3
2
1 x
x
x
Iteration # The estimate of the solution vector at the end of Iteration #1 is
3
2
1 x
x
x
Now we get ( ) ( )
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
>> Moff = M - diag( diag( M ) ) Moff = 0 - 2 3
>> 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.
Exercise 2.1: [ 3 ]
19 Numerical Methods – Bisection, False Position and Secant Method
Objective
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.
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);