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!