Can't get plot to work
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2021-3-25
%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 个评论
Walter Roberson
2021-3-25
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.
更多回答(1 个)
KSSV
2021-3-25
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))
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!