How to make my Newton's method accept an array of values?

19 ビュー (過去 30 日間)
David Ademe
David Ademe 2016 年 9 月 29 日
回答済み: Harsha Phadke 2016 年 10 月 3 日
Hi everyone, I have written the following code to take scalar values and give me the root. However, this homework question that I have asks me to manipulate the code to do the following: "The polynomial f(x) = x^3 − 2x^2 − 11x + 12 has roots 4, −3, and 1. Write a function that creates an array x of 1, 000 initial guesses on the interval [−3, 4] and runs Newton’s method with tolerance 10−8 for each initial guess (remember to comment out any plot commands or print to screen commands in your newton.m or you may have 1000 plots come up). Store the root for each initial guess in the array p, and plot p against x (use a ylim([-5 5]) command to set the y axis). From your plot, what, approximately, is the basin of attraction for the root 1?"
Here's the code I've written for Newton's method:
f=@(x) ((x.^3)-(2*x.^2)-(11*x)+12);
df=@(x) ((3*x.^2)-(4*x)-11);
x1=linspace(-3,4,1000);
y1=f(x1);
y2=df(x1);
tol= 10^(-6);
c=0;
x2=(x1-(y1/y2));
while abs(x2-x1)>tol;
c=c+1;
x1=x2;
y1=f(x1);
y2=df(x1);
x2=(x1-(y1/y2));
end
fprintf('The root of the equation is=%f',x2)
c=c
How would I change the code that I've written to accept the array and plot the values? I'm extremely lost and confused. Thank you very much in advance, I really appreciate it.
  1 件のコメント
James Tursa
James Tursa 2016 年 9 月 29 日
The easiest thing for you to do is get your scalar version of the code and wrap that in a loop, saving the result of each loop iteration in a vector.

サインインしてコメントする。

回答 (1 件)

Harsha Phadke
Harsha Phadke 2016 年 10 月 3 日
Hey David,
It seems that there is a flaw in the code you have posted. As you may notice, your code generates three(1X1000) matrices for variables x1,y1 & y2. These matrices will help you find the first approximation for each of these 1000 initial guesses. For this the line
x2 = (x1-(y1/y2));
should be changed to:
x2 = (x1-(y1./y2));
Thus the vector x2 will serve as a vector of first approximations for the 1000 initial guesses. Then, you have to iterate on each of the elements of x2, till it finds a close enough solution.
You can try to modify the code in the following link inorder to achieve your workflow: https://www.mathworks.com/matlabcentral/fileexchange/28227-newton-s-method/content/newton.m
Note that the information contained in the above link is written by a third-party user and hence I will not be able to comment on its accuracy. You might consider contacting the third-party user directly in case of any issues.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by