MATLAB Syntax for Numerical Methods (Unit 1 & Unit 2)
Unit I - Solution of Equations and Eigenvalue Problems
1. Fixed Point Iteration Method:
function [root] = fixed_point_iteration(f, x0, tol, max_iter)
for i = 1:max_iter
x1 = f(x0);
if abs(x1 - x0) < tol
break;
end
x0 = x1;
end
root = x1;
end
2. Newton-Raphson Method:
function [root] = newton_raphson(f, df, x0, tol, max_iter)
for i = 1:max_iter
x1 = x0 - f(x0)/df(x0);
if abs(x1 - x0) < tol
break;
end
x0 = x1;
end
root = x1;
end
3. Gauss Elimination Method:
function x = gauss_elimination(A, b)
n = length(b);
for k = 1:n-1
for i = k+1:n
factor = A(i,k)/A(k,k);
A(i,k:n) = A(i,k:n) - factor*A(k,k:n);
b(i) = b(i) - factor*b(k);
end
end
x = zeros(n,1);
x(n) = b(n)/A(n,n);
for i = n-1:-1:1
x(i) = (b(i) - A(i,i+1:n)*x(i+1:n))/A(i,i);
end
end
4. Gauss-Seidel Iterative Method:
function x = gauss_seidel(A, b, x0, tol, max_iter)
n = length(b);
x = x0;
for k = 1:max_iter
x_old = x;
for i = 1:n
x(i) = (b(i) - A(i,[1:i-1 i+1:n])*x([1:i-1 i+1:n]))/A(i,i);
end
if norm(x - x_old, inf) < tol
break;
end
end
end
Unit II - Interpolation and Approximation
1. Lagrange Interpolation:
function P = lagrange_interpolation(x, y, x0)
n = length(x);
P = 0;
for i = 1:n
L = 1;
for j = 1:n
if i ~= j
L = L * (x0 - x(j))/(x(i) - x(j));
end
end
P = P + y(i) * L;
end
end
2. Newton's Divided Difference Interpolation:
function P = newton_divided_difference(x, y, x0)
n = length(x);
coef = zeros(n,n);
coef(:,1) = y';
for j = 2:n
for i = 1:n-j+1
coef(i,j) = (coef(i+1,j-1) - coef(i,j-1))/(x(i+j-1) - x(i));
end
end
P = coef(1,1);
for i = 2:n
term = coef(1,i);
for j = 1:i-1
term = term * (x0 - x(j));
end
P = P + term;
end
end
3. Cubic Spline Interpolation:
function pp = cubic_spline(x, y)
pp = spline(x, y);
end