Effacer les filtres
Effacer les filtres

my code is runing but I can not get the plot out

1 vue (au cours des 30 derniers jours)
wenchong chen
wenchong chen le 4 Avr 2021
Commenté : DGM le 4 Avr 2021
hi, here is my code, the plot windows pop out but there is no pot on them, whats wrong with my code?
hold on
f = @(x) x.^3 - (9)*x.^2 + 3.8197
xl = -1000
xu = 1000
iter = 1
xm = (xl+xu)/2
error = 20
while error > 0.001
if (f(xm).*f(xl))<0
xu=xm
xm2 = (xl+xu)/2
error = (xm2-xm)/xm2
error = abs(error)
xm = xm2
else
xl=xm
xm2 = (xl+xu)/2
error = (xm2-xm)/xm2
error = abs(error)
xm = xm2
end
xm= (xl+xu)/2
subplot(2,1,1)
plot(iter,xm)
subplot(2,1,2)
plot(iter,error)
iter = iter + 1;
end

Réponses (2)

Walter Roberson
Walter Roberson le 4 Avr 2021
subplot(2,1,1)
plot(iter, xm, '*-')
subplot(2,1,2)
plot(iter, error, '*-')
  2 commentaires
wenchong chen
wenchong chen le 4 Avr 2021
not working well
Walter Roberson
Walter Roberson le 4 Avr 2021
subplot(2,1,1)
plot(iter, xm, '*-')
hold on
subplot(2,1,2)
plot(iter, error, '*-')
hold on
Your existing hold does not apply to the new axes you created by subplot()

Connectez-vous pour commenter.


DGM
DGM le 4 Avr 2021
Modifié(e) : DGM le 4 Avr 2021
You're trying to plot things inside a loop. That usually ends up just creating headaches. Store the results to vectors and then plot the vectors. Since we don't know how long the vectors will be, I just chose to let them grow as necessary.
Try this:
clf
f = @(x) x.^3 - (9)*x.^2 + 3.8197
xl = -1000
xu = 1000
iter = 1
xm = (xl+xu)/2
error = 20
xmvec=[];
errvec=[];
while error > 0.001
if (f(xm)*f(xl))<0
xu=xm
xm2 = (xl+xu)/2
error = (xm2-xm)/xm2
error = abs(error)
xm = xm2
else
xl=xm
xm2 = (xl+xu)/2
error = (xm2-xm)/xm2
error = abs(error)
xm = xm2
end
xmvec=[xmvec (xl+xu)/2];
errvec=[errvec error];
iter = iter + 1;
end
subplot(2,1,1)
plot(1:iter-1,xmvec)
subplot(2,1,2)
plot(1:iter-1,errvec)
  2 commentaires
wenchong chen
wenchong chen le 4 Avr 2021
this worked, thank you very much.
I got it , that what I was thinking but I dont know how to do. what is the iter doing in the second line under while? so for both xmvec and errvec, the loop will add one number to vectors automaticly?
DGM
DGM le 4 Avr 2021
That lone iter line was just something I threw in there so I could see what was going on. I didn't mean to include that.
Yes. The vectors will grow in length since x=[x x2] is concatenation of x and x2. It is the same thing as cat(2,x,x2).
Generally, making arrays grow in a loop isn't good practice. It's slow, but for something like this where the vectors are small, the task is noncritical, and we don't know the final size to begin with, I'd say it's acceptable.

Connectez-vous pour commenter.

Community Treasure Hunt

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

Start Hunting!

Translated by