I can not plot my Matlab code

3 次查看(过去 30 天)
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
  2 个评论
Adam Danz
Adam Danz 2019-4-11
The code you shared doesn't produce a fugure at all. Also, 'xi' is nowhere present in your code.
hgrlk
hgrlk 2019-4-11
I know, I erase the code of plot that i wrote. Because it didn't give me anything.
xi is x in my code, I didn't mentioned sorry about that.

请先登录,再进行评论。

采纳的回答

Adam Danz
Adam Danz 2019-4-11
编辑:Adam Danz 2019-4-12
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')
  2 个评论
hgrlk
hgrlk 2019-4-14
thank you, but in my code i musn't change the while loop as for. because in the question it is given "use while and if". But i think it will work with"while loop" too.
Adam Danz
Adam Danz 2019-4-15
Yes, it should work with a while loop as well. Let me know if you have any trouble implementing that change.

请先登录,再进行评论。

更多回答(0 个)

Community Treasure Hunt

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

Start Hunting!

Translated by