0% found this document useful (0 votes)
100 views

Intro - Matlab - and - Numerical - Method Lab Full Document

The document provides an introduction to MATLAB and numerical methods. It discusses key topics such as: - MATLAB's advantages of being easy to use, having powerful built-in routines and toolboxes, and being popular in academia and industry. - Basic MATLAB commands like % for comments, ; to suppress output, and ... to continue statements across lines. - How to perform basic math operations, work with arrays and matrices, use intrinsic math functions and constants, format output, make plots, and use loops and conditional statements like if/else. - Examples are provided to demonstrate how to work with numbers, arrays, matrices, loops, conditional statements, plotting, and other MATLAB features and functions.

Uploaded by

Eyu Kaleb
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
100 views

Intro - Matlab - and - Numerical - Method Lab Full Document

The document provides an introduction to MATLAB and numerical methods. It discusses key topics such as: - MATLAB's advantages of being easy to use, having powerful built-in routines and toolboxes, and being popular in academia and industry. - Basic MATLAB commands like % for comments, ; to suppress output, and ... to continue statements across lines. - How to perform basic math operations, work with arrays and matrices, use intrinsic math functions and constants, format output, make plots, and use loops and conditional statements like if/else. - Examples are provided to demonstrate how to work with numbers, arrays, matrices, loops, conditional statements, plotting, and other MATLAB features and functions.

Uploaded by

Eyu Kaleb
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

University of Gondar

Introduction to MATLAB and


numerical methods
Compiled by: Habtamu G.

Mechanical Engineering: Numerical methods Computational


structure

2015 E.C.
1.Introduction
• The name MATLAB stands for MATrix LABoratory
➢It is good at dealing with matrices
➢Vendor’s website: http//:www.mathworks.com

• Advantages of MATLAB
➢Ease of use
➢Powerful built-in routines and toolboxes (LOTS!!!)
➢Good visualization of results
➢Popularity in both academia and industry

• Disadvantages of MATLAB
➢Can be slow (MATLAB is an interpreted language)
➢Must be licensed (it’s not free :)
Basic Commands

a) % used to denote a comment

b) ; suppresses display of value (when placed at end of


a statement)

c) ... continues the statement on next line

d) eps machine epsilon

e) inf infinity

f) NaN not-a number, e.g., 0/0.


Numbers
• To change format of numbers:
format long, format short, etc.
See “help format”.
• Mathematical functions: sqrt(x), exp(x), cos(x), sin(x),
sum(x), etc.
• Operations: +, -, *, /
• Constants: pi, exp(1), etc.
Managing the workspace

➢clear t
>> clears variable t
➢clear
>> clears all variables
➢clear all
>> clears all variables, globals, functions, and MEX
links
➢To clear the Command Window
>> clc
➢To clear the current figure
>> clf
➢To abort a MATLAB computation
ctrl-C
2. Matlab Program Highlight
Write your first Matlab program
>> a = 3;
>> b = 5;
>> c = a+b
Output:
8
The semicolon at the end of a statement acts to suppress
output (to keep the program running in a "quiet mode"). The
third statement, c= a+b, is not followed by a semicolon so
the content of the variable c is "dumped" as the output.

6
The meaning of "a = b"
• In Matlab and in any programming language, the statement "a =
b" does not mean "a equals b". Instead, it prompts the action of
replacing the content of a by the content of b.

>> a = 3;
>> b = a;
>> b
Output:
3

7
Basic math operations
>> a=3;
>> b=9;
>> c=2*a+b^2-a*b+b/a-10

c=

53

• Remark: The right hand side of the third statement includes


all 4 of the basic arithmetic operators, +, - ,*, and / in their
usual meaning. It also includes the symbol, ^, which means
"to the power of", so "b^2" means (the content of b) to the
power of 2, i.e., 9 ^2 = 81.

8
Arrays
>> a = [3 6 7];
>> b = [1 9 4];
>> c = a + b

Output:

4 15 11
Remarks: (1) Both a and b are given as a three-element array. In the third line,
the operation of "a+b" results in element-by-element addition

9
Continued……
Extracting an individual element of an array
>> a = [3 6 7];
>> b = [1 9 4 5];
>> c = a(2) + b(4)
Output:
c = 11

Remark: If b is a one-dimensional array, b(n) is the n-


th element of that array. Since a(2) is 6 and b(4) is 5,
the 3rd statement leads to c = 6+5 = 11
10
Comment
%
% This program demonstrates how to "comment out"
% a segment of code
%
A = 3;
B = A*A;
%
% B = 2*B <--- This statement is not executed
%
C = A+B
Output:
c = 12

11
Continuation to next line
>> summation1=1+3+5+7 ...
+ 9 + 11

Note: The three periods (...) allow continuation to the next line of
commands. The two lines in the above example are essentially one line of
"summation1 = 1+3+5+7+9+11".

12
Input: Request user input

% example
prompt = ‘What is the original value? ‘;
x = input(prompt);
y = x*10
disp('job done') % for printing a certain statement
fprintf('job done \n') % alternative for printing a statement

13
Intrinsic math functions and constants
>> x = pi;
>> y = sin(pi/2)
>> z = exp(-sin(pi/2))
>> a=2^(log(4));
>> b=sqrt(9);

Output:
y=1
z = 0.367

• Remarks: "pi" (= 3.14159...) is a reserved intrinsic constant. A function


within a function is allowed. The inner most function will be evaluated first,
so the 3rd statement leads to z = exp(-1) = 0.3679.9

14
Format:
format(style) changes the output display format to the format
specified by style.
For example, format("shortG") displays numeric values in a
compact form with 5 total digits.

% example: please check the result of the following


pi
format short
pi
format long
pi

15
Making a quick plot

x =0:pi/100:2*pi;
y = sin(x);
plot(x,y)

16
Making a multiple plot
x = linspace(-2*pi,2*pi);
y1 = sin(x);
y2 = cos(x);
Figure=plot(x,y1,x,y2)

x = 0:pi/100:2*pi;
y1 = sin(x);
y2 = sin(x-0.25);
y3 = sin(x-0.5);

figure= plot(x,y1,x,y2,'--',x,y3,':’)
% line style

17
Making a multiple plot

x = 0:pi/100:2*pi;
y1 = 2*cos(x);
y2 = cos(x);
y3 = 0.5*cos(x);
plot(x,y1,'--',x,y2,'-',x,y3,':')
xlabel('0 \leq x \leq 2\pi')
ylabel('Cosine functions')
legend('2*cos(x)','cos(x)','0.5*cos(x)')
title('Typical example of multiple plots')

18
2. Arrays and matrix's
To create an array with four elements in a single row, separate the elements
with either a comma (,) or a space.

>> z=[12 3 4 3]
To create a matrix that has multiple rows, separate the rows with semicolons.

Matrix operation is also allowed

% example
a = [ 1 2 3 ; 4 5 6; 7 8 9];
b = [ 7 5 6 ; 2 0 8; 5 7 1];
c = a + b % matrix addition
d=a-b
e=a*b
19
Basic looping
The for loop: to repeat specified number of times

for v = 1.0:-0.2:0.0
disp(v)
end

Output
1
for i = 1:2:7 0.8000
0.6000
x=i^2;
0.4000
end 0.2000
x 0
20
The for loop: example
clear all
alpha = 0.143;
U(1) = 0.5;
for k=2:4
U(k) = (1-alpha)*U(k-1);
end
U

Output:
U=
0.5000 0.4285 0.3672 0.3147

21
For loop: More on the dummy index
sum1 = 0;
for k = 1:9
sum1 = sum1+k;
end
sum1

Output:
45
Remark: this program performs the summation of
1+2+3+4+5+6+7+8+9 (= 45).

22
For loop: More on the dummy index
sum1 = 0;
for k = 1:2:9
sum1 = sum1+k;
end
sum1

Output:
25
Remark: this program performs the summation of 1+3+5+7+9 (= 25).
The command "for k = 1:2:9" means we go through the loop only 5
times. First time with k = 1, second time with k = 1+2 (=3), third time
with k = 1+2+2 (=5), and so on. The looping stops once k reaches 9.

23
Treatment of array within a loop
b = [3 8 9 4 7 5];
sum1 = 0;
for k = 1:4
sum1 = sum1+b(k);
end
sum1

Output:
24
Remark: This program performs the summation of sum1 =
b(1)+b(2)+b(3)+b(4) = 3+8+9+4 = 24

24
Double loop
sum1 = 0;
for n = 1:2
for m = 1:3
sum1 = sum1+n*m;
end
end
sum1

• Output:
• 16
• Remark: this program performs the summation of Sum1 =
1*1+1*2+1*3 +2*1+2*2+2*3 = 18

25
More complicated use of loop and index
b = [2 5 7 4 9 8 3];
c = [2 3 5 7];
sum1 = 0;
for k = 1:4
sum1 = sum1+b(c(k));
end
sum1

Output:
24
Remark: This program performs the summation of
sum1 = b(c(1))+b(c(2))+b(c(3))+b(c(4))
= b(2)+b(3)+b(5)+b(7)
= 5+7+9+3
= 24
26
if, elseif, else
Execute statements if condition is true

% example
x=5;
if(x==5)
Y=7
else
Y=0
end

27
Continued…..
• There are 6 commonly used expressions to compare
two numbers in an if command:
• A > B A is greater than B
• A < B A is less than B
• A >= B A is greater than or equal to B
• A <= B A is less than or equal to B
• A == B A equals B
• A ~= B A does not equal B

28
if, elseif, else

% example 2
a = 12;
minvalue = 3;
maxvalue = 7;
if (a <= minvalue) &&(a>=maxvalue)
disp ('Hello1')
elseif (a > maxvalue)
disp('Hello2')
else
disp('Hello3')
end

29
if, elseif, else
% example 3
a = 100;
%check the boolean condition
if a == 10
% if condition is true then print the following
fprintf('Value of a is 10\n' );
elseif( a == 20 )
% if else if condition is true
fprintf('Value of a is 20\n' );
elseif a == 30
% if else if condition is true
fprintf('Value of a is 30\n' );
else
% if none of the conditions is true ‘
fprintf('None of the values are matching\n’);
fprintf('Exact value of a is: %d\n', a );
end

30
While loops

x=7;
while (x >= 0)
x = x-2;
end
x

% Result: This computes x = 7-2-2-2-2 = -1.


Mod(a,b) is for reminder c
•The "mod(A,B)" function returns the remainder
of A divided by B.
•For example, mod(7,2) = 1, mod(10,4) = 2, and
mod(25,5) = 0. If A is divisible by B, mod(A,B)
= 0.

32
Combine looping and branching
% more example
sum1 = 0,sum2 = 0, N = 9;
for k = 1:N
sum1 = sum1+k;
if (mod(k,3) == 0)
sum2 = sum2+k;
end
end
sum1,sum2

Output:
sum1 = 45
sum2 = 18

Remark: Sum1 = 1+2+3+4+5+6+7+8+9, while sum2 = 3+6+9.


33
Reference
• http://www.mathworks.com/help/matlab/
•https://www.mathworks.com/support/learn-
with-matlab-tutorials.html
•https://www.tutorialspoint.com/matlab/inde
x.htm
•http://engineering.nyu.edu/mechatronics/vk
apila/matlabtutor.html

34
Part II
Numerical analysis

35
Estimate the solution set of
f(x) = sin 10x + cos 3x
using graphical method. The plot on
the matlab/exel should be [0 5]

36
Bi-section method: iteration
number as stopping criteria

37
% 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 38
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 39
False position method:

Exercise: write a matlab code that can solve


the following function using a false position
method.

40
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%.

41
Simple Fixed-Point iteration
clear all, clc
% Setting x as symbolic variable
syms x;

g = input('Enter non-linear equations: ');


x1 = input('Enter first guess: ');
e = input('Tolerable error in decimal: '); % basic criterion

er=1; % error initialization


fprintf('x1\t\t\ter\n');
while er>e
x1_old=x1;
x1 = eval(subs(g,x,x1));
er=abs((x1-x1_old)/x1); % new error distribution
fprintf('%f\t\t%f\n',x1,er);
end
fprintf('\nRoot is: %f\n', x1);

42
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%.

43
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);
44
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;

f = input('Enter non-linear equations: ');


a = input('Enter first guess: ');
b = input('Enter second guess: ');
iteration = input('Enter the the numeber of iteration: '); % basic criterion
er=1; % error intialization

%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);

45
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

46
47
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]

48
Referencing the Elements of a Matrix

Generally we use: mx(m, n);


For example, to refer to the element in the 2nd row and 5th column,
of the matrix a, as created in the last section, we type

To reference all the elements in the mth column we type


A(:,m).

49
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

50
MATLAB
Addition & Subtraction of Matrices

Both the operand matrices must have the same number of


rows and columns.

51
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.

52
MATLAB –
Transpose of a Matrix

The transpose operation switches the rows and columns in a


matrix. It is represented by a single quote(').

53
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.

54
MATLAB
Determinant of a Matrix

determinant of a matrix is calculated using the det


function of MATLAB. Determinant of a matrix A is given
by det(A).

55
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).

56
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.

57
Cramer's rule 3x3 by matlab

https://habtedu.blogspot.com/search/label/Cramer%27s%20Rule
https://youtu.be/IkeqErjubvs 58
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); 59
Gaussian Elimination by matlab

https://habtedu.blogspot.com/search/label/Gaussian%20Elimination
60
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
61
fprintf('x =\t%f\n:',x)
Exercise for you

Solve using LU Decomposition method


using MATLAB

https://youtu.be/nKkOwzJmJzs
https://habtedu.blogspot.com/search/label/LU%20decomposition 62
Gauss-Seidel using matlab to
solve systems of linear
equation

https://habtedu.blogspot.com/search/label/Gauss-Seidel%20method
https://youtu.be/wGqVDitGvoo 63
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); 64
Fit a 2nd order polynomial to the given data
using least square Regression using
MATLAB
xi 0 1 2 3 4 5
yi 2.1 7.7 13.6 27.2 40.9 61.1

https://habtedu.blogspot.com/search/label/Least%E2%80%90Square%20Regression
https://youtu.be/rRQ32buCAuE 65
clear all
disp('General formula of 2nd Least SQ. Regression: y=a0+a1x+a2*x^2')
A=[0 1 2 3 4 5];
B=[2.1 7.7 13.6 27.2 40.9 61.1];
n=length(A);
A2=A.^2 %yield element-by-element multiplication of both matrices
A3=A.^3
A4=A.^4
AB=A.*B
A2B=A2.*B
% define Summation
sum_A=sum(A)
sum_A2=sum(A2) Part one
sum_A3=sum(A3)
sum_A4=sum(A4)
sum_B=sum(B)
sum_AB=sum(AB)
sum_A2B=sum(A2B)
% Construct the summ matrix
C=[n sum_A sum_A2; sum_A sum_A2 sum_A3; sum_A2 sum_A3 sum_A4]
D=[sum_B; sum_AB;sum_A2B]
%Now apply crammer's rule
66
%Now apply crammer's rule
% The coefficient matrix as C and D
detC = det(C);
% Compute the determinant of C with column 1 replaced by D
detC1 = det([D C(:,2:3)]);
detC2 = det([C(:,1) D C(:,3)]);
detC3 = det([C(:,1:2) D]);
% Compute the solutions using Cramer's Rule
a0 = detC1 / detC
a1 = detC2 / detC
a2 = detC3 / detC
% Print the solutions to the console Part two
% fprintf('y=%f+%f*x+%f*x^2',a0,a1,a2)
syms x;
disp(‘let we want to show the function f')
% Define the function
f=a0+a1*x+a2*x^2
y=simplify(f)
%example
x_cal=1.5
fx = eval(subs(y,x,x_cal))

67
Newton’s Divided-Difference
Interpolation

Exercise: Write a matlab code for generating


Newton interpolation of order three for the
following data set:

i 0 1 2 3 4
0 1 2 3 4
0 1 8 27 64

Source
https://youtu.be/0iapf2TwDoE 68
Lagrange interpolation using
matlab

Exercise: Lagrange interpolation of order three


for the following data set:

i 0 1 2 3 4
0 1 2 3 4
0 1 8 27 64

https://youtu.be/GLCN2puLtTU
69
Trapezoidal rule of Integration
Example: Integrate the following function from 0 to
0.8 using 10 segments trapezoidal rule

f (x) = 0.2 + 25x − 200x 2 +675x 3− 900x 4 + 400x 5


n−1
I = [f (x 0 ) + 2 f (x i ) + f (x n )]
h
OR
2 i=1

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)]);

71
Application Simpson’s 1/3 Rule
Example: Integrate the following function from 0 to 0.8
using 4 segments Simpson rule

f (x) = 0.2 + 25x − 200x 2 +675x 3− 900x 4 + 400x 5

Source
https://youtu.be/hgDzdUJPBsw 72
Three sample size- Application Simpson’s 3/8 Rule

3
I  h [f (x 0 ) + 3f (x 1 ) + 3f (x 2 ) + f (x 3 )]+
8
3
h [f (x 3 ) + 3f (x 4 ) + 3f (x 5 ) + f (x 6 )] +
8
3
h [f (x 6 ) + 3f (x 7 ) + 3f (x 8 ) + f (x 9 )]
8
73
Simpson’s 3/8 Rule
% Let us construct a function Function definition
function I = simpson38()
% SIMPSON38 Simpson's 3/8 rule for numerical integration.
% I = SIMPSON38(f, a, b, n) approximates the definite integral of f
% from a to b using Simpson's 3/8 rule with n segments.
% The function f must accept a vector argument.
f = input(' the function like: @(x) 0.2+ 25*x-200*x.^2 + 675*x.^3-900*x.^4+400*x.^5');
a = input('lower limit eg. 0'); % lower limit of integration
b = input ('upper limit of the integration: eg. 0.8'); % upper limit of integration
n = input ('Number of segments eg. 10*3');
h = (b-a)/n; % h is the length of the segment
x = linspace(a, b, n+1); % define the varation
y = f(x);
% I is the simpson's 3/8 Rule
I = 3*h/8*(y(1) + 3*sum(y(2:3:end-2)) + 3*sum(y(3:3:end-1)) + 2*sum(y(4:3:end-3)) + y(end));
end
% Finally save with respect to the function name
% Now let us call this function using another script

Function Calling
Result:
% call the function 1.6329
I = simpson38(); % approximate integral value
disp(I)

https://youtu.be/orbggRn5QyM
74
https://habtedu.blogspot.com/search/label/Simpson%27s%203%2F8%20rule
Class assignment 5%
For the following data set, make a three order
curve fitting using Lagrange interpolation on
Matlab.
During the analysis you should show:
a. the function f(x) on the result
b. Do or check for f(1.5)

i 0 1 2 3 4
0 1 2 3 4
0 1 8 27 64

75

You might also like