MATLAB Answers

# help me in trying to solve the secant method

1 view (last 30 days)
Ishmum Monjur Nilock on 10 Feb 2020
Edited: Jim Riggs on 10 Feb 2020
Hello all I try to write the code for secant method below:
clear all
close all
clc
n=100;
err=0.004;
x0=0.5;
x1=1;
x(1)=x0;
x(2)=x1;
f=@(x) exp(-x)-x;
i=0;
for i=3:n
x(i) = x(i-1) - (f(x(i-1)))*((x(i-1) - x(i-2))/(f(x(i-1)) - f(x(i-2))));
i=i+1;
if abs((x(i)-x(i-1))/(x(i)))*100 < err %in this line
root=x(i);
break
end
end
When i try to run the code it says that error index exceeds the maximum array elements(3) in the line no specified with green comment. How to solve the problem? Is there any way so that I can run the program from here?
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Answers (1)

Jim Riggs on 10 Feb 2020
Edited: Jim Riggs on 10 Feb 2020
Try preallocating x, right after you define n:
n = 100;
x = nan(1,n);
...
##### 1 CommentShowHide None
Jim Riggs on 10 Feb 2020
I just noticed that you are incrementing your loop variable "i" inside the loop.
This is usually a bad idea.
the line "for i=3:n" controls the value of i. When i gets to a value of n, then you add 1 to i, so i is now n+1.
The way that your loop is written now, x(i) is defined on each pass of the loop. When you increment i, you are trying to reference x(i+1) which does not yet exist. If you preallocate the way I suggested, then x(i+1) will exist, but it will be defined as "nan". Either way, you will have a problem with this construct.

Sign in to comment.

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by