MATLAB Numerical Methods

Optimized for fast loading & copy-paste

1. Runge-Kutta Method

function [dxdy] = rk(x,y)
    dxdy=2*x^3+12*x^2-2*x+8.5
end

% SCRIPT
clc;
h = 0.5;
x0 = 0;
y0 = 1;
n = 1;
for k=1:1
    k1 = h * rk(x0);
    k2 = h * rk(x0 + h/2);
    k3 = h * rk(x0 + h/2);
    k4 = h * rk(x0 + h);
    y = y0 + (k1 + 2*k2 + 2*k3 + k4) / 6;
    y0 = y;
end
disp("Solution: y1 = ")
disp(y)

2. Newton Raphson Method

function [y] = newton1(x)
    y = exp(-x) - x;
end
function [y1] = newton2(x)
    y1 = -exp(-x) - 1;
end

% SCRIPT
clc;
fprintf("Newton Raphson's Problem\n");
xold = 0;
xnew = 0;
for i = 1:4
    a = newton1(xold);
    b = newton2(xold);
    xnew = xold - (a / b);
    fprintf("n = %d: xold = %f, xnew = %f\n", i, xold, xnew);
    xold = xnew;
end

3. Lagrange Interpolation

% Given data
x0 = 5; x1 = 6; x2 = 9; x3 = 11;
y0 = 12; y1 = 13; y2 = 14; y3 = 16;
x = 10;

% Lagrange Interpolation Formula
y = (((x - x1) * (x - x2) * (x - x3)) / ((x0 - x1) * (x0 - x2) * (x0 - x3))) * y0 + ...
    (((x - x0) * (x - x2) * (x - x3)) / ((x1 - x0) * (x1 - x2) * (x1 - x3))) * y1 + ...
    (((x - x0) * (x - x1) * (x - x3)) / ((x2 - x0) * (x2 - x1) * (x2 - x3))) * y2 + ...
    (((x - x0) * (x - x1) * (x - x2)) / ((x3 - x0) * (x3 - x1) * (x3 - x2))) * y3

4. Euler's Method

function a = eulers_fn(x,y)
    a = x + y + x*y;
end

% SCRIPT
x = 0;
y = 1;
h = 0.025;
while x < 0.1
    y = y + h * eulers_fn(x,y);
    x = x+h;
end
y
x

5. Bisection Method

function [f] = bisectionl(x)
    f = -0.4*x^2+2.2*x+4.7
end

% SCRIPT
clc;
a=5;
b=10;
q=bisectionl(a)*bisectionl(b); % Fixed function name typo
x0=a;
x1=b;
iter_count=0;
if(q<0)
    while(abs(x1-x0)>0.0001)
        xn=(x0+x1)/2;
        if(bisectionl(x0)*bisectionl(xn)>0)
            x0=xn;
            x1=x1;
        else
            x0=x0;
            x1=xn;
            t=[x0 x1 xn];
        end
        iter_count=iter_count+1;
    end
end
iter_count
t=[x0 x1 xn]

6. Trapezoidal Rule

function [y] = trap(x)
    %main function
    y=0.2+25*x-200*x^2+675*x^3-900*x^4+400*x^5;
end
function [y1] = trap1(x)
    %Integrated function
    y1=0.2*x+(25*x^2)/2-(200*x^3)/3+(675*x^4)/4-(900*x^5)/5+(400*x^6)/6;
end

% SCRIPT
a=0;
b=0.8;
Iact=trap1(b)-trap1(a)

%Trapazoidal rule 
n=2;
h=(b-a)/(n);

%Single Application of trapazoidal rule 
I1=(b-a)*(trap(b)+trap(a))/2
error1=((Iact-I1)/Iact)*100

%Multiple Application of trapazoidal rule
 I2=(h/2)*(trap(a)+(2*trap(h))+trap(b))
error2=((Iact-I2)/Iact)*100

7. Simpson's 1/3 and 3/8 Rules

function [y] = trap(x)
    %main function
    y=0.2+25*x-200*x^2+675*x^3-900*x^4+400*x^5;
end
function [y1] = trap1(x)
    %Integrated function
    y1=0.2*x+(25*x^2)/2-(200*x^3)/3+(675*x^4)/4-(900*x^5)/5+(400*x^6)/6;
end

%Simpson's 1/3rd rule
a=0; b=0.8;
Iact=trap1(b)-trap1(a);
n1=4;
h1=(b-a)/(n1);

%Single Application of Simpson's 1/3rd rule
I3=((b-a)/6)*(trap(0)+(4*trap(0.4))+trap(0.8))
error3=((Iact-I3)/Iact)*100

%Multiple Application of Simpson's 1/3rd rule
I4=(h1/3)*(trap(0)+4*(trap(0.2)+trap(0.6))+2*trap(0.4)+trap(0.8))
error4=((Iact-I4)/Iact)*100

%Simpson's 3/8th rule
h=(b-a)/3;
error1=((Iact-I1)/Iact)*100 % Requires I1 from prev context
x0=0;
x1=0.2666;
x2=0.5333;
x3=0.8;
I1=((3*h)/8)*(trap(x0)+(3*trap(x1))+(3*trap(x2))+trap(x3))

8. Curve Fitting

%1)Straight line linear fitting.
x=[5 10 20 50 100];
y=[15 33 53 140 301];
plot(x,y,'o');
title('Mrinal Gupta 1st question');
xlabel('X-Axis');
ylabel('Y-Axis');   

%2) Quadratic and cubic fitting
x1=0:pi/30:pi/3;
y1=sin(x1) + rand(size(x1))/100;
plot(x1,y1,'o');
title('Mrinal Gupta 2nd question');
xlabel('X-Axis');
ylabel('Y-Axis');

%3) Spring constant calculation
m=[5 10 20 50 100];
del=[15.5 33.07 53.39 140.24 301.03];
g=9.81;
F=m/1000*g;
a=polyfit(del,F,1);
del_fit=0:10:300;
F_fit=polyval(a,del_fit);
plot(del,F,'o',del_fit,F_fit);
title('Mrinal Gupta 3rd question');
xlabel('Displacement \delta (mm)');
ylabel('Force (N)');
k=a(1);
text(100,.32,['\leftarrow Spring const k = ',num2str(k),' N/mm']);

9. 10 Images (Plotting Exercises)

%1) Simple line plot
x=0:0.05:5
y=sin(x.^2)
plot(x,y)

%2) Plot two y1 and y2 vs x
x=0:0.05:5
y1=sin(x.^2)
y2=cos(x.^2)
plot(x,y1)
plot(x,y2)

%3) Hold on/off plot
x1=linspace(0,2*pi,100)
y3=sin(x1)
plot(x1,y3)
hold on
y4=cos(x1)
plot(x1,y4)
hold off

%4) Bar plot
x2=-2.9:0.2:2.9
y5=exp(-x2.*x2)
bar(x2,y5)

%5) Stair plot
x3=0:0.25:10
y6=sin(x3)
stairs(x3,y6)

%6) Polar plot
theta=0:0.01:2*pi
rho=abs(sin(2*theta).*cos(2*theta))
polarplot(theta,rho)

%7) 3-D stem plot (simple)
x4=linspace(-pi/2,pi/2,40)
z=cos(x4)
stem3(z)

%8) 3-D stem plot (matrix)
x5=-pi/2:0.1:pi/2
y7=sin(x5)
y8=cos(x5)
data=[x5' y7' y8']
stem3(data(:,1), data(:,2), data(:,3), 'filled')
title('3-D Stem Plot')
xlabel('x'); ylabel('sin(x)'); zlabel('cos(x)')

%9) 3-D stem with curve and view
x6=linspace(-5,5,60)
y9=cos(x6)
z1=x6.^2
data1=[x6' y9' z1']
stem3(data1(:,1), data1(:,2), data1(:,3), 'filled')
hold on
plot3(data1(:,1), data1(:,2), data1(:,3), 'Color', 'red')
hold off
view(-8,30)
title('3-D Stem Plot with Curve')

%10) 3-D stem circle
theta1=0:0.1:2*pi
x7=cos(theta1)
y10=sin(theta1)
z2=theta1
stem3(x7, y10, z2, ':m', 'Marker', '*', 'MarkerSize', 8, 'LineWidth', 1)
hold on
plot3(x7, y10, z2, 'Color', 'red')
hold off
title('3-D Stem Plot with Circle')

10. Array Operations

% Define the array for daily temperatures
daily_temperatures = [25, 28, 26, 29, 30, 27, 24];
% Display the array
disp('Daily Temperatures:');
disp(daily_temperatures);

% Define the matrix for student scores
student_scores = [
    85, 92;  % Student 1: Test 1, Test 2 scores
    78, 88;  % Student 2: Test 1, Test 2 scores
    90, 85   % Student 3: Test 1, Test 2 scores
];
% Display the matrix
disp('Student Scores:');
disp(student_scores);

11. Arithmetic Operations

%1) Assign a=3
a=3
%2) Assign b=a+2
b=a+2
%3) Assign C=bxa
c=b*a
%4) Assign d= b/c
d=b/c

%5) Define A as 2x3 matrix of values 1 2 3 4 5 6
A=[1 2 3;4 5 6]

%6) Create a vector of 'm' 3 equally spaced values
m=5
B=linspace(1,10,m)

%7) Create vector of start valve 2 end valve 10 with 5 values
C=linspace(2,10,5)

%8) Create ones mxm matrix
ones(m)

%9) Create zeros mxm matrix
zeros(m)

%10) Create x matrix with 3x3
X=rand(3,3)

%11) Use sine and inverse sine
s1=sind(30); s2=asind(0.5);

%12) Use cosine and inverse cosine
c1=cosd(60); c2=acosd(1);

%13) Use tan and inverse tan
t1=tan(pi/4); t2=atan(1);

%14) Use sec and inverse sec
sc1=sec(pi/3); sc2=asec(sc1);

%16) Use cosec and inverse cosec
cosc1=cscd(30); cosc2=acscd(cosc1);

%17) Use cot and inverse cot
ct1=cot(pi/6); ct2=acot(1);

%18) For x matrix find absolute value of x, find exponential value of x.
Y=abs(X)
Z=exp(X)

%19) Use sqrt, log and round in built function.
a1=sqrt(4); a2=log(10); a3=log10(10); a4=round(pi);

12. Graph 2D and 3D

%Data from your table
T = [0 1 2 3 4 5 6 7 8 9 10];
Temp = [0 11 19 28 40 49 61 69 78 91 100];

% 2D Plot
figure;
plot(T, Temp, 'o-b', 'LineWidth', 2);
xlabel('Time (min)');
ylabel('Temperature (°C)');
title('2D Plot of Time vs Temperature');
grid on;

% 3D Plot
Z = Temp.*2;
figure;
plot3(T, Temp, Z, 'o-r', 'LineWidth', 2);
xlabel('Time (min)');
ylabel('Temperature (°C)');
zlabel('Z value');
title('3D Plot Example');
grid on;