Skip to content

Commit 4e11e16

Browse files
authored
Create secant.m
1 parent 17e51e6 commit 4e11e16

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

secant.m

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
function [rootVal,EaFinal,i,elapsedTime] = secant(f,x1,x2,stoppingErrorCriteria,maxIterations)
2+
tic
3+
xVect = zeros(maxIterations,1);
4+
Ea = xVect;
5+
xVect(1,1) = x1;
6+
xVect(2,1) = x2;
7+
8+
for i=2:maxIterations
9+
xVect(i+1,1) = xVect(i,1)-(f(xVect(i,1))*(xVect(i-1,1)-xVect(i,1))/( f(xVect(i-1,1))-f(xVect(i,1))));
10+
Ea(i,1) = 100*abs((xVect(i,1)-xVect(i-1,1))/xVect(i,1));
11+
ifNaN = any(xVect(i+1,1));
12+
if ifNaN == 0
13+
xVectFinal(1:i,1) = xVect(1:i,1);
14+
EaVectFinal(1:i+1,1) = Ea(1:i+1,1);
15+
break
16+
end
17+
if i>1 && Ea(i,1)<stoppingErrorCriteria
18+
xVectFinal(1:i,1) = xVect(1:i,1);
19+
EaVectFinal(1:i+1,1) = Ea(1:i+1,1);
20+
break
21+
end
22+
end
23+
rootVal = xVectFinal(end,1);
24+
EaFinal = EaVectFinal(end,1);
25+
i = i-1;
26+
plot(-14:0.01:5,f(-14:0.01:5),'k')
27+
grid on; hold on
28+
plot(xVectFinal(end,1),f(xVectFinal(end,1)),'b*')
29+
plot(xVectFinal,f(xVectFinal),'go')
30+
xlabel('x'); ylabel('y(x)')
31+
elapsedTime = toc;
32+
end

0 commit comments

Comments
 (0)