Practical 7-10 BSc VI Sem_240527_180417
Practical 7-10 BSc VI Sem_240527_180417
Practical 7-10 BSc VI Sem_240527_180417
B.Sc. Sem VI
Practical (Using MATLAB)
% Example usage
x = [0, 1, 2, 3, 4];
y = [1, 2, 1, 0, 1];
xx = linspace(0, 4, 100); % Interpolation points
lagrange_interpolation(x, y, xx);
Note: This will plot the original data points and the interpolated polynomial. We can adjust
the data points and interpolation points as needed for our specific problem.
Practical 8. To write programs for implementation of the Simpson's 1/3 rule for
numerical integration in MATLAB.
Program:
function integral_value = simpsons_rule(f, a, b, n)
% Check if n is even
if mod(n, 2) ~= 0
% Step size
h = (b - a) / n;
% Initialize sum
sum_odd = 0;
sum_even = 0;
% We can use this function by passing the function f(x), the limits of integration a and b, and
% Example usage
f = @(x) sin(x); % Define the function
a = 0; % Lower limit of integration
b = pi; % Upper limit of integration
n = 100; % Number of subintervals
integral_value = simpsons_rule(f, a, b, n);
4 1 0 1
1 3 1 0
0 1 2 1
1 0 1 4
Program:
% Define the matrix A
A = [4, -1, 0, 1;
-1, 3, -1, 0;
0, -1, 2, -1;
1, 0, -1, 4];
% Define the initial guess for the eigenvector
v = [1; 1; 1; 1];
% Set the number of iterations
num_iterations = 100;
% Power method iteration
for i = 1:num_iterations
% Multiply A by the current eigenvector
Av = A * v;
% Calculate the magnitude of Av
eigenvalue = norm(Av);
% Normalize Av to get the next eigenvector approximation
v = Av / eigenvalue;
end
disp('Dominant eigenvalue:');
disp(eigenvalue);
disp('Eigenvector:');
disp(v);
Output:
Dominant eigenvalue:
5.278413609496445
Eigenvector:
0.708049776672887
-0.258904520246109
-0.118158193818664
0.646275950645789
Note: In this example, we have a 4x4 matrix A. We initialize an arbitrary guess for the
eigenvector v. Then, in the iteration loop, we repeatedly multiply A by the current
eigenvector approximation, normalize the result to obtain the next approximation of the
eigenvector, and update the eigenvalue estimate. After a sufficient number of iterations,
eigenvalue will converge to the dominant eigenvalue of A, and v will converge to its
corresponding eigenvector.
Practical 10. To write a program to find solution and plot its graph for the
following second-order ordinary differential equation (ODE) using the fourth-
order Runge-Kutta method in MATLAB:
+2 + 2𝑦 = sin (𝑡)
Program:
% Define the ODE functions
f1 = @(t, y, v) v;
f2 = @(t, y, v) sin(t) - 2*v - 2*y;
% Number of steps
N = (tspan(2) - tspan(1)) / h;
Note: 1. We can convert this second-order ODE into a system of two first-order ODEs and
2
𝑑 𝑦
then solve it using the fourth-order Runge-Kutta method. Let 𝑣 = , so that = . Then
𝑑𝑡2
we have:
= 𝑣 and = sin(t)−2v−2y.
2. This code defines the system of first-order ODEs, then implements the fourth-order Runge-
Kutta method to compute the solution at each time step. Finally, it plots the solution y(t).