Can't get plot to work
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Matt Baron
am 25 Mär. 2021
Kommentiert: Matt Baron
am 27 Mär. 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 Kommentare
Akzeptierte Antwort
Walter Roberson
am 25 Mär. 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 Kommentare
Walter Roberson
am 25 Mär. 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.
Weitere Antworten (1)
KSSV
am 25 Mär. 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 Kommentare
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices 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!