How to make my Newton's method accept an array of values?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
James Tursa
el 29 de Sept. de 2016
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.
Respuestas (1)
Harsha Phadke
el 3 de Oct. de 2016
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.
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!