I can not plot my Matlab code
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
hgrlk
am 11 Apr. 2019
Kommentiert: Adam Danz
am 15 Apr. 2019
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 Kommentare
Adam Danz
am 11 Apr. 2019
The code you shared doesn't produce a fugure at all. Also, 'xi' is nowhere present in your code.
Akzeptierte Antwort
Adam Danz
am 11 Apr. 2019
Bearbeitet: Adam Danz
am 12 Apr. 2019
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')
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/213423/image.jpeg)
2 Kommentare
Adam Danz
am 15 Apr. 2019
Yes, it should work with a while loop as well. Let me know if you have any trouble implementing that change.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Introduction to Installation and Licensing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!