MATLAB Answers

help me in trying to solve the secant method

조회 수: 6(최근 30일)
Ishmum Monjur Nilock
Ishmum Monjur Nilock 2020년 2월 10일
편집: Jim Riggs 2020년 2월 10일
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?

답변(1개)

Jim Riggs
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
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.

댓글을 달려면 로그인하십시오.

태그

Community Treasure Hunt

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

Start Hunting!

Translated by