MATLAB Answers

Solved the graph. Drawed the function. How to plot the x solution marked with a ring...

1 view (last 30 days)
Britney
Britney on 14 Oct 2014
Answered: Siddharth Sundar on 15 Oct 2014
Okay, I feel stupid for asking this question but it has annoyed me to far.
I have drawn a graph and solved the f(x)=0 and I know want to plot one x value. This is what I have come up with:
%%my_newton
function x=my_newton(f,Df,x0,tol)
x=x0;kmax=10; tol=1e-8;
for k=1:kmax
d=-f(x)/Df(x);
x=x+d;
%disp([x d])
if abs(d)<tol, break
end
end
msg=sprintf('Warning.');
if k==kmax, disp(msg);
end
%%Graph
clf
f=@(x)0.5*(x-2).^2-2*cos(2*x)-1.5;
x=linspace(-3,7);
plot(x,f(x))
axis([-3 7 -5 10]);grid on
hold on
%%Solution
f=@(x)0.5*(x-2).^2-2*cos(2*x)-1.5;
Df=@(x)x+4*sin(2*x)-2;
x=my_newton(f,Df,[-0.4],1e-8)
plot(x,y,':om') % <-----correct or not?
x=my_newton(f,Df,[1.1],1e-8)
x=my_newton(f,Df,[1.9],1e-8)
x=my_newton(f,Df,[3.8],1e-8)
It does what I want to but I feel that there must be a smarter way to do this than "one by one" function. If repeat the same step on [1.1] I get another ring. Can I plot these four points in one formula?

Answers (1)

Siddharth Sundar
Siddharth Sundar on 15 Oct 2014
I would suggest that you rework your code in the function my_newton to handle multiple x0 values in one call by passing a vector of x0 values you want to evaluate the function for.
Also, make sure that you return a vector of x values from the function. You can use the vector of values to then generate the corresponding 'f(x)' values before plotting it with one single plot command.
You can read documentation about Vectorization in MATLAB which talks in general about the process of revising loop-based, scalar oriented code to use MATLAB matrix and vector operations.

Community Treasure Hunt

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

Start Hunting!