MATLAB: I can not plot the Matlab code

helpMATLABnewton raphsonplotting

Hello,
I want to plot my code, but when i write the code there is no line in the graph. I want 2 graphs, one is f(x) versus i and one is x versus i. Also how can I write a function for the circle mark for each data point in the function? ( I use Matlab R2015a )
Thank you..
clc
clear all
close all
fprintf('%10s %10s %10s %10s %10s\n','i','xi','f(xi)','diff_f(xi)','|Ea|')
x = 0;
i = 1;
while i <= 50
f = @(x) x^3 - x - 3 ;
diff = @(x) 3*(x^2) - 1 ;
xnew = x - (f(x) / diff(x));
if abs(((xnew-x)/xnew)*100) < 10^(-3)
break
end
fprintf('%10.4f %10.4f %10.4f %10.4f %10.4f\n',i,x,f(x),diff(x),abs((xnew-x)/xnew)*100)
x = xnew;
i =i+1;
end

Best Answer

On each iteration of your while-loop you were overwriting the x variable instead of stored the value for each iteration.
Here is a re-write of your code with the following significant chages. I tested the first and last row of the outputs for my version and your version and they are identical.
  • I moved the anonymous functions outside of the loop and changed the internal variable names to z
  • I changed your function name "diff" to "dif" since matlab already has a function named "diff"
  • Your x variable is allocated prior to the loop so it can store the value from each iteration.
  • The while-loop was replaced with a for-loop.
  • Everything within the loop was restructured and simplified.
  • At the end of the for-loop, we're storing the x variable value for each iteration.
fprintf('%10s %10s %10s %10s %10s\n','i','xi','f(xi)','diff_f(xi)','|Ea|')
f = @(z) z^3 - z - 3 ;
dif = @(z) 3*(z^2) - 1 ;
x = NaN(1,50);
for i = 1:50
if i == 1
tempX = 0;
else
tempX = xnew;
end
xnew = tempX - (f(tempX) / dif(tempX));
if abs(((xnew-tempX)/xnew)*100) < 10^(-3)
break
end
fprintf('%10.4f %10.4f %10.4f %10.4f %10.4f\n',i,tempX,f(tempX),dif(tempX),abs((xnew-tempX)/xnew)*100)
x(i) = xnew; %
end
If you want to plot f(x) vs i,
subplot(1,2,1)
plot(1:50, f([0, x(1:end-1)]))
xlabel('i')
ylabel('f(x)')
If you want to plot x vs i,
subplot(1,2,2)
plot(1:50, x)
xlabel('i')
ylabel('x')