Numerical Methods Lab Part 2
Numerical Methods Lab Part 2
2015 E.C.
Part II
Numerical analysis
2
Estimate the solution set of
f(x) = sin 10x + cos 3x
using graphical method. The plot on
the matlab/exel should be [0 5]
3
Bi-section method: iteration
number as stopping criteria
4
% Application of Bisection in Root finding
clear all, clc
syms x; % Setting x as symbolic variable Bi-section method: iteration
y = input('Enter non-linear equations: ');
a = input('Enter lower limit: '); number as stopping criteria
b = input('Enter upper limit: ');
iteration = input('maximum Iteration: '); % basic stoping criterion
er=100; % error initialization
%evaluation of f(x) for the boundary conditions
fa = eval(subs(y,x,a));
fb = eval(subs(y,x,b));
% Implementing Bisection Method
if fa*fb > 0
disp('Given initial values do not bracket the root.');
else
c = (a+b)/2;
fc = eval(subs(y,x,c));
fprintf('\n\na\t\tb\t\tc\t\ter\t\tf(c)\n');
fprintf('%f\t%f\t%f\t%f\t%f\n',a,b,c,fc, er);
for i = 1:iteration-1 % since the iteration starts before for loop
if fa*fc< 0
b =c;
c = (a+b)/2;
er=abs((c-b)/c)*100; % new error distribution
else
a =c;
c = (a+b)/2;
er=abs((c-a)/c)*100;
end
fc = eval(subs(y,x,c));
fa = eval(subs(y,x,a));
fb = eval(subs(y,x,b));
fprintf('%f\t%f\t%f\t%f\t%f\n',a,b,c,fc, er);
end
fprintf('\nRoot is: %f\n', c);
end 5
clear all, clc
% Application of Bisection in Root finding
syms x; % Setting x as symbolic variable
y = input('Enter non-linear equations: ');
a = input('Enter lower limit: ');
b = input('Enter upper limit: ');
e = input('Tolerable error in decimal: '); % basic stoping criterion
er=1; % error initialization
fa = eval(subs(y,x,a));
fb = eval(subs(y,x,b));
% Implementing Bisection Method
if fa*fb > 0
disp('Given initial values do not bracket the root.');
else
c = (a+b)/2;
fc = eval(subs(y,x,c)); Bi-section method:
fprintf('\n\na\t\tb\t\tc\t\tf(c)\n');
fprintf('%f\t%f\t%f\t%f\n',a,b,c,er); Approximate error number as
while er>e stopping criteria
if fa*fc< 0
b =c;
c = (a+b)/2;
er=abs((c-b)/c); % new error distribution
else
a =c;
c = (a+b)/2;
er=abs((c-a)/c);
end
fc = eval(subs(y,x,c));
fa = eval(subs(y,x,a));
fb = eval(subs(y,x,b));
fprintf('%f\t%f\t%f\t%f\n',a,b,c,er);
end
fprintf('\nRoot is: %f\n', c);
end 6
False position method:
7
Simple Fixed-Point iteration
Ex: Using simple fixed-point iteration, determine
the root of the function f(x)=e-x-x using initial
guess of x=0 and a<40%.
8
Simple Fixed-Point iteration
clear all, clc
% Setting x as symbolic variable
syms x;
9
Newton Raphson
method for root
finding
Ex: Use the Newton-Raphson method to
determine the root of the function f(x)=e-x-x
using x=0 as an initial guess, and percent
relative error less than 0.1%.
10
Newton Raphson method for root
finding
clear all, clc
syms x; % Setting x as symbolic variable
f = input('Enter non-linear equations: ');
x1 = input('Enter intial guess: ');
e = input('Tolerable error in decimal: '); % basic stoping criterion
er=1; % error initialization
df=diff(f); % differentiation
fprintf('x1\t\t\ter\n');
while er>e
x1_old=x1;
fx = eval(subs(f,x,x1));
dfx = eval(subs(df,x,x1));
x1=x1-(fx/dfx); % Newton rapson methodolgy of iteration
er=abs((x1-x1_old)/x1); % new error distribution
fprintf('%f\t\t%f\n',x1,er);
end
fprintf('\nRoot is: %f\n', x1);
11
Secant method for root finding
% coded for educational purpose at university of Gondar
% Mechanical department
% Secant method
clear all, clc
% Setting x as symbolic variable
syms x;
%fprintf('i\t\t\xi\t\t\xi\t\t\c\t\t\ter\n');
fprintf('\n\ni\t\t\txi_1\t\t\txi\t\t\tx\t\t\ter\n');
fa = eval(subs(f,x,a));
fb = eval(subs(f,x,b));
c=b-(fb*(a-b)/(fa-fb));
ite=1; %simply for showing figure, iteration number one
fprintf('%f\t\t%f\t\t%f\t\t%f\t\t%f\n',ite,a,b,c,er);
for i=1:iteration-1
c_old=c;
a=b;
b=c;
fa = eval(subs(f,x,a));
fb = eval(subs(f,x,b));
c=b-(fb*(a-b)/(fa-fb));
er=abs((c-c_old)/c); % new error destribtion
fprintf('%f\t\t%f\t\t%f\t\t%f\t\t%f\n',i+1,a,b,c,er);
end
fprintf('\nRoot is: %f\n', c);
12
For more and theoretical aspect visit:
https://habtedu.blogspot.com/search/label/Bisection%20using%20
MATLAB
https://habtedu.blogspot.com/search/label/Fixed%20point%20iter
ation
https://habtedu.blogspot.com/search/label/Newthon-
Rapson%20method
https://habtedu.blogspot.com/search/label/Secant%20method
13
14
Matrix
By entering elements in each row as comma
or space delimited numbers and using
semicolons to mark the end of each row.
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]
15
Referencing the Elements of a Matrix
16
Referencing the Elements of a Matrix
You can also select the elements in the mth through nth columns,
for this we write
a(:,m:n)
To do this, write
17
MATLAB
Addition & Subtraction of Matrices
18
MATLAB
Division (Left, Right) of Matrices
You can divide two matrices using left (\) or right (/) division
operators.
Both the operand matrices must have the same number of rows
and columns.
19
MATLAB –
Transpose of a Matrix
20
MATLAB –
Matrix Multiplication
The elements of the rows in the first matrix A are multiplied
with corresponding columns in the second matrix B.
It is possible only if the number of columns n in A is equal to
the number of rows n in B.
21
MATLAB
Determinant of a Matrix
22
MATLAB
Inverse of a Matrix
Inverse of a matrix in MATLAB is calculated using
the inv function. Inverse of a matrix A is given by
inv(A).
23
Concatenating Matrices
▪ You can concatenate two matrices to create a larger matrix. The pair of
square brackets '[]' is the concatenation operator.
▪ When you concatenate two matrices by separating those using
commas, they are just appended horizontally-called horizontal
concatenation.
▪ Alternatively, if you concatenate two matrices by separating those
using semicolons, they are appended vertically-vertical concatenation.
24
Cramer's rule 3x3 by matlab
https://habtedu.blogspot.com/search/label/Cramer%27s%20Rule
https://youtu.be/IkeqErjubvs 25
Cramer's rule 3x3 by matlab
%% Using crammers rule to fined solution of equations
%Define the coefficient matrix A and the constant vector B
% As Ax=B
A = [-0.5 0.52 1; 0.5 1 1.9; 0.1 0.3 0.5];
B = [-0.01; 0.67; -0.44];
% Compute the determinant of A
detA = det(A);
% Compute the determinant of A with column 1 replaced by B
detA1 = det([B A(:,2:3)]);
% Compute the determinant of A with column 2 replaced by B
detA2 = det([A(:,1) B A(:,3)]);
% Compute the determinant of A with column 3 replaced by B
detA3 = det([A(:,1:2) B]);
% Compute the solutions using Cramer's Rule
x1 = detA1 / detA;
x2 = detA2 / detA;
x3 = detA3 / detA;
% Print the solutions to the console
fprintf('x1 = %f\n', x1);
fprintf('x2 = %f\n', x2);
fprintf('x3 = %f\n', x3); 26
Gaussian Elimination by matlab
https://habtedu.blogspot.com/search/label/Gaussian%20Elimination
27
https://youtu.be/KCN8dfPNOBY
Gaussian Elimination by matlab
% Define the coefficient matrix A and the constant vector B with Pivoting
A = [5 -2 0; 1 2 -1;0 -3 7 ];
B = [2 ; 3 ; 2];
% Combine A and B into an augmented matrix AB
AB = [A B];
[m, n] = size(AB); % Get the size of the matrix AB
% Perform row operations to reduce the matrix AB to upper triangular form
for i = 1:m-1 % loop over each row except the last row
for j = i+1:m % loop over each row below the current row
% Compute the factor to multiply the current row by
factor = AB(j,i) / AB(i,i);
% Subtract a multiple of the current row from the lower row
AB(j,:) = AB(j,:) - factor * AB(i,:)
end
end
% Back-substitute to solve for x
x = zeros(m, 1); % initialize x as a column vector of zeros
x(m) = AB(m,n) / AB(m,m) % compute the last element of x ||column
for i = m-1:-1:1 % loop over each row in reverse order
sum = AB(i,n); % initialize sum as the right-hand side constant
for j = i+1:m % loop over each column to the right of the current row
sum = sum - AB(i,j) * x(j) % subtract the product of the coefficient and the corresponding element of
x
end
x(i) = sum / AB(i,i); % divide the remaining constant by the coefficient
end
28
fprintf('x =\t%f\n:',x)
Exercise for you
https://youtu.be/nKkOwzJmJzs
https://habtedu.blogspot.com/search/label/LU%20decomposition 29
Gauss-Seidel using matlab to
solve systems of linear
equation
https://habtedu.blogspot.com/search/label/Gauss-Seidel%20method
https://youtu.be/wGqVDitGvoo 30
clear all, clc
%format long
% Define the coefficient matrix A and the constant vector b
A = [3 -0.1 -0.2; 0.1 7 -0.3; 0.3 -0.2 10];
b = [7.25; -19.3; 71.4];
% Choose an initial guess for x and set the tolerance and maximum number of iterations
x0 = [0; 0; 0];
tol = 1e-6;
max_iter = 100;
% Initialize the solution vector x, the iteration counter iter, and the error measure error
x = x0;
iter = 0;
error = tol + 1;
fprintf('iter\t\t\tx(1)\t\t\tx(2)\t\t\tx(3)\t\t\terror\n');
% Implement the Gauss-Seidel algorithm
while error > tol && iter < max_iter
% Save the old value of x for error calculation
x_old = x;
% Calculate the new value of x(i) using the Gauss-Seidel formula
x(1) = (b(1) - A(1,2)*x_old(2) - A(1,3)*x_old(3)) / A(1,1);
x(2) = (b(2) - A(2,1)*x(1) - A(2,3)*x(3)) / A(2,2);
x(3) = (b(3) - A(3,1)*x(1) - A(3,2)*x(2)) / A(3,3);
% Calculate the relative error between the old and new values of x
error = norm(x - x_old) / norm(x);
% Increment the iteration counter
iter = iter + 1;
fprintf('%f\t\t%f\t\t%f\t\t%f\t\t%f\n',iter,x(1),x(2),x(3),error);
end
% Display the solution and the number of iterations
fprintf('Solution: x =\n');
disp(x);
fprintf('Number of iterations: %d\n', iter); 31
Lagrange interpolation using
matlab
i 0 1 2 3 4
0 1 2 3 4
0 1 8 27 64
https://youtu.be/GLCN2puLtTU
32
Trapezoidal rule of Integration
Example: Integrate the following function from 0 to
0.8 using 10 segments trapezoidal rule
n−1
f (x 0 ) + 2 f (x i ) + f (x n )
OR
I = (b − a) i=1
2n
Refer
https://youtu.be/adaozQTVOrk
https://habtedu.blogspot.com/search/label/Trapezoidal%20rule
Trapezoidal rule of Integration
% Trapezoidal Rule
% Define the function to be integrated
f = @(x) 0.2+ 25*x-200*x.^2 + 675*x.^3-900*x.^4+400*x.^5;
% Define the integration limits
a = 0; Result:
b = 0.8; Approximated integral using
the trapezoidal rule: 1.615
% Define the number of subintervals
n = 10;
% Compute the width of each subinterval
h = (b-a)/n;
% Compute the approximated integral using the trapezoidal rule
integral_approx = (h/2)*(f(a) + 2*sum(f(a+h:h:b-h)) + f(b));
% Display the result || num2str:converts integers into character
disp(['Approximated integral using the trapezoidal rule: ', num2str(integral_approx)]);
34