help me in trying to solve the secant method
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Jim Riggs
2020-2-10
编辑:Jim Riggs
2020-2-10
Try preallocating x, right after you define n:
n = 100;
x = nan(1,n);
...
1 个评论
Jim Riggs
2020-2-10
编辑:Jim Riggs
2020-2-10
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!