MATLAB Code For NumericalA
MATLAB Code For NumericalA
MATLAB Code For NumericalA
Code
clc
clf
close all
clear all
syms x y
f = x - y^2;
x1 = input('Enter the lower value of x: ');
x2 = input('Enter the upper value of x: ');
y0 = input('Enter the initial value of y: ');
N = input('Enter the number of iterations: ');
Y(1) = y0;
for i = 2:N+1
Y(i) = y0 + int(subs(f, y, Y(i-1)), x, x1, x2);
fprintf('y(%.1f) = %f \n', x1 + (i-1)*(x2 - x1)/N, Y(i))
end
Code
clc
clear all
syms x y
for i=1:n
y(i+1)=y(i) + h*f(x(i), y(i) );
x(i+1) = x0 + i*h;
fprintf('y(%.2f) = %.4f\n', x(i+1), y(i+1))
end
MATLAB code for Modified Eular’s Method
Code
clc
clear all;
f = input('Enter the function (Right hand side of ODE :');
x0 = input('Enter initial value of independent variable :');
y0 = input('Enter initial value of dependent variable :');
h = input ('Enter Step Size :');
xn = input ('Enter the point at which you want to evaluate :');
n = (xn-x0)/h;
x(1) = x0; y(1)= y0;
for i=1:n+1
ys=y(i) + h*f(x(i), y(i) );
x(i+1) = x0 + i*h;
y(i+1)=y(i)+(h/2)*(f(x(i),y(i))+f(x(i+1), ys));
fprintf('y(%.2f) = %.4f\n', x(i+1), y(i+1))
end
Code
%Matlab code for sin(x)
clc;
close all;
f=@(x) (1/x);
h = (b-a)/n;
s0 = f(a) + f(b);
s1 = 0;
for i =1: n-1
x = a + i*h;
s1 = s1 + f(x);
end
Code
clc
close all
clear all
A = [2 2 1; 1 3 1; 1 2 2];
[V, D] = eig(A);
disp('Eigenvalues:');
disp(diag(D));
disp('Eigenvectors:');
disp(V);
Code
clc
clear all
close all
f = @(x) cos(x);
a = input('Enter Lower Limit = ');
b = input('Enter Upper Limit = ');
n = input('Enter Interval = ');
h = (b-a)/n;
if rem(n,2)==1
fprintf('Please enter valid interval... \n');
n = input('Enter Interval as even number = ');
end
k = 1:1:n-1;
s = f(a+k.*h);
se = sum(s(2:2:n-1));
so = sum(s(1:2:n-1));
Code
clc
clear all
close all
f = @(x) cos(x);
a = input('Enter Lower Limit = ');
b = input('Enter Upper Limit = ');
n = input('Enter Interval = ');
h = (b-a)/n;
if rem(n,3)==0
fprintf('Thanks its a valid interval... \n');
else
n = input('\n Enter Interval as multiplier of 3 = ');
end
k = 1:1:n-1;
i = 3:3:n-1;
s = f(a+k.*h);
s3 = sum(s(i));
s(i) = [];
so = sum(s);
Code
clc
clear all
close all
n = (xn-x0)/h;
x(1) = x0; y(1)= y0;
for i=1:n
x(i+1)=x0+i*h;
k1 = h*f(x(i),y(i));
k2 = h*f(x(i)+(h/2),y(i)+(k1/2));
k3 = h*f(x(i)+(h/2),y(i)+(k2/2));
k4 = h*f(x(i)+h,y(i)+k3);
y(i+1) = y(i) + (1/6)*(k1+2*k2+2*k3+k4);
fprintf('y(%.2f) = %.4f\n', x(i+1), y(i+1))
end
MATLAB code for Newton Rapshon Method
Code
clc
% Input Section
y = input('Enter non-linear equations: ');
a = input('Enter initial guess: ');
e = input('Tolerable error: ');
N = input('Enter maximum number of steps: ');
% Initializing step counter
step = 1;
while abs(fa)> e
fa = eval(subs(y,x,a));
ga = eval(subs(g,x,a));
if ga == 0
disp('Division by zero.');
break;
end
b = a - fa/ga;
fprintf('step=%d\ta=%f\tf(a)=%f\n',step,a,fa);
a = b;
if step>N
disp('Not convergent');
break;
end
step = step + 1;
end