MATLAB Answers

I need to print both the plots on the same figure but i cannot get the hold on command to work. Is there an explanation for this? Is there something wrong with my code? Its only showing the second plot.

2 views (last 30 days)
Derek Paul
Derek Paul on 10 Feb 2017
Edited: Stephen Cobeldick on 10 Feb 2017
eqn = 'Dy =y+2* cos(x)';
ini = 'y(0)=-2';
y=dsolve(eqn,ini,'x');
x1 = linspace(0,0.1,2);
y1 = eval(vectorize(y));
xlabel('x')
ylabel('y')
title('Derek Paul Section 202 - exp(x) - 2^(1/2)*cos(x + pi/4)')
x2 = [0.000000 0.200000 0.400000 .600000 0.800000 1.000000 1.200000 1.400000 1.600000 1.800000 2.000000]
y2 = [-2.000000 -2.000000 -2.00797 -2.041144 -2.119238 -2.264403 -2.501163 -2.856452 -3.359756 -4.043387 -4.942945]
plot(x1,y1);
hold on
scatter(x2,y2,'r','filled');

  3 Comments

Stephen Cobeldick
Stephen Cobeldick on 10 Feb 2017
@Derek Paul: Nothing, that is why I did not put it as an answer. Some people are interested to learn ways that they can improve their code. It is like when you go to the mechanic to get the tail light fixed, and they say "you need to replace your brake pads soon". Free advice, yours to ignore if you want to.

Sign in to comment.

Answers (1)

Steven Lord
Steven Lord on 10 Feb 2017
Line 6, where you eval the symbolic expression, doesn't work. I assume you mean to substitute x1 into y? As written, it substitute x into y, but there's no variable named x.
If you change that line to:
y1 = subs(y, 'x', x1);
the code works. It may not look like the plot command plotted the data, but if you zoom in on the range where x goes from 0 to 0.1 and y goes from -2.01 to -2 you'll see a line connecting the two points whose coordinates are in x1 and y1.

  0 Comments

Sign in to comment.

Sign in to answer this question.