matlab8&9
matlab8&9
%Taylor Series
%To solve y' = 2*y+3*exp(x), y(0) = 0
close all;
clear all;
x0 = 0;
y0 = 0;
xEnd = 0.4;
h = 0.1;
n = (xEnd - x0)/h;
%Initialising Solutions
x = (x0:h:xEnd)';
y = zeros(n+1,1);
y(1) = y0;
for i = 1:n
dy1 = 2*y(i) + 3*exp(x(i));
dy2 = 2*dy1 + 3*exp(x(i));
dy3 = 2*dy2 + 3*exp(x(i));
dy4 = 2*dy3 + 3*exp(x(i));
%Taylor's series solution
y(i+1) = y(i)+h*dy1+(h^2)*dy2/factorial(2)+(h^3)*dy3/factorial(3)+
(h^4)*dy4/factorial(4);
end
sol = [x,y]
%Plot the solution curve
plot(x,y);
title('Solution Curve')
OUTPUT:
sol =
0 0
0.1000 0.3487
0.2000 0.8112
0.3000 1.4167
0.4000 2.2011
%Program
%Modified Euler Method
%To solve for f(x,y) = x+sqrt(y), y(0) = 1, h = 0.2
%For the range 0<x<0.4
close all;
clear all;
f = @(x,y)x + sqrt(y);
x0 = 0;
y0 = 1;
xEnd = 0.4;
h = 0.2;
n = (xEnd - x0)/h;
%Initialising Solutions
x = (x0:h:xEnd)';
y = zeros(n+1,1);
y(1) = y0;
for i = 1:n
y1p = y(i) + h*f(x(i),y(i));
y1c = y(i) + (h/2)*(f(x(i),y(i))+f(x(i+1),y1p));
err = abs(y1p-y1c);
while err>0.0001
y1c = y(i) + (h/2)*(f(x(i),y(i))+f(x(i+1),y1p));
err = abs(y1p-y1c);
y1p = y1c;
end
y(i+1) = y1c;
end
sol = [x,y]
%Plot the solution curve
plot(x,y)
title('Solution Curve')
OUTPUT:
sol =
0 1.0000
0.2000 1.2309
0.4000 1.5254
%Area under curve
clc;
close all;
clear all;
syms x f(x)
f(x) = input('Enter the integrand:\n');
x0 = input('Enter the lower limit:\n');
xn = input('Enter the upper limit:\n');
n = input('Enter the number of intervals:\n');
h = (xn-x0)/n;%Calculating the step size of intervals
xinit = x0;
for i = 1:n+1 %Generating x values
x(i) = xinit;
xinit = x(i) + h;
end
for i = 1:n+1 %Generating y values
y(i) = subs(f, x(i));
end
%Trapezoidal Rule
Area_by_Trapezoidal_Rule = (h/2)*((y(1)+y(n+1))+2*(sum(y)-y(1)-y(n+1)))
fprintf('Trapezoidal Rule method can be applied only for even number of
intervals.');
OUTPUT:
Area_by_Trapezoidal_Rule = 492480797/2515460454
Trapezoidal Rule method can be applied only for even number of intervals.
Area_by_1_3rd_Rule = 3697753984/18865953405
Area_by_3_8th_Rule = 1643452019/8384868180