MATLAB Source Code 2
MATLAB Source Code 2
% Clearing Screen
clc
% Input Section
y = input('Enter non-linear equations: ');
a = input('Enter first guess: ');
b = input('Enter second guess: ');
e = input('Tolerable error: ');
a b c f(c)
% Clearing Screen
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
Root is 0.739085
MATLAB Code: Secant Method
% Secant Algorithm
% Find the root of y = cos(x) from 0 to pi.
f = @(x) (cos(x));
p0 = input('Enter 1st approximation, p0: ');
p1 = input('Enter 2nd approximation, p1: ');
n = input('Enter no. of iterations, n: ');
i = 2;
f0 = f(p0);
f1 = f(p1);
while i <= n
p = p1-f1*(p1-p0)/(f1-f0);
fp = f(p);
if abs(p-p1) < tol
fprintf('\nApproximate solution p = %11.8f\n\n',p);
break;
else
i = i+1;
p0 = p1;
f0 = f1;
p1 = p;
f1 = fp;
end
end
MATLAB Output
>> Untitled7
% Secant Algorithm
% Find the root of y = x^3+3x^2-1 from 0 to pi.
f = @(x) (x^3+3*x^2-1);
p0 = input('Enter 1st approximation, p0: ');
p1 = input('Enter 2nd approximation, p1: ');
n = input('Enter no. of iterations, n: ');
i = 2;
f0 = f(p0);
f1 = f(p1);
while i <= n
p = p1-f1*(p1-p0)/(f1-f0);
fp = f(p);
if abs(p-p1) < tol
fprintf('\nApproximate solution p = %11.8f\n\n',p);
break;
else
i = i+1;
p0 = p1;
f0 = f1;
p1 = p;
f1 = fp;
end
end
MATLAB Output
>> Untitled7