Can't get plot to work
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Matt Baron
le 25 Mar 2021
Commenté : Matt Baron
le 27 Mar 2021
Hello Mathworks team!
I created this Euler's method code below but can't get the graph to show anything at all. Even if I make a separate code with just xn=1 yn=1, plot(xn,yn), the graph shows up but nothing on it. Any help would be much appreciated.
%Euler's Method
h=.25;%step size
xinitialcondition=0;%initial condition for x
yinitialcondition=1;%initial condition for y
n=0;%start at 0
xn=xinitialcondition;
yn=yinitialcondition;
f=@(xn,yn) (2*(cos(xn))*yn);%the function to be evaluated
while xn < 10%what value do you want it estimated to
xn = (xinitialcondition) + ((n) .* (h));
[n xn yn]
yn = (yn) + ((h) .* f(xn,yn));
if xn >= 10
break
end
plot(xn,yn,"r-")
hold on
n=n+1;
end
hold off
0 commentaires
Réponse acceptée
Walter Roberson
le 25 Mar 2021
%Euler's Method
h=.25;%step size
xinitialcondition=0;%initial condition for x
yinitialcondition=1;%initial condition for y
n=0;%start at 0
xn=xinitialcondition;
yn=yinitialcondition;
f=@(xn,yn) (2*(cos(xn))*yn);%the function to be evaluated
while xn < 10%what value do you want it estimated to
xn = (xinitialcondition) + ((n) .* (h));
[n xn yn]
yn = (yn) + ((h) .* f(xn,yn));
if xn >= 10
break
end
plot(xn,yn,"r-*") %CHANGED
hold on
n=n+1;
end
hold off
2 commentaires
Walter Roberson
le 25 Mar 2021
plot() only draws a line if there are two adjacent finite values in the same call. You are only plotting one point at a time, so it cannot draw lines.
Plus de réponses (1)
KSSV
le 25 Mar 2021
Save into a Matrix and plot all at once:
%Euler's Method
h=.25;%step size
xinitialcondition=0;%initial condition for x
yinitialcondition=1;%initial condition for y
n=0;%start at 0
xn=xinitialcondition;
yn=yinitialcondition;
f=@(xn,yn) (2*(cos(xn))*yn);%the function to be evaluated
A = zeros([],2) ;
while xn < 10%what value do you want it estimated to
xn = (xinitialcondition) + ((n) .* (h));
yn = (yn) + ((h) .* f(xn,yn));
if xn >= 10
break
end
n=n+1;
A(n,:) = [xn yn] ;
end
plot(A(:,1),A(:,2))
6 commentaires
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!