I am trying to plot multiple step sizes on a single plot
Using nested for loops to plot multiple approximations of Eulers method
조회 수: 1 (최근 30일)
이전 댓글 표시
%%Improved Eulers
clear all;
F=@(x,y) -cos(x*y);
Xnum(1)=1;
Ynum(1)=3;
Xf=2;
Ypred(1)=Ynum;
figure(2)
hold on
for hstep = 1/16:1/2:1/128
Numsteps=(Xf-Xnum(1))/hstep;
for k = 1:Numsteps:1000
Xnum(k+1) = Xnum(k) + hstep;
Ypred(k+1)= Ynum(k)+hstep*F(Xnum(k),Ynum(k));
Ynum(k+1) = Ynum(k) + hstep*0.5*(F(Xnum(k),Ynum(k))+F(Xnum(k+1),Ypred(k+1)));
end
plot(Xnum,Ynum)
end
답변 (1개)
John D'Errico
2020년 2월 20일
편집: John D'Errico
2020년 2월 20일
Smile. Think about what you did. I think I know what you wanted to achieve, but look more carefully at what you have here.
for hstep = 1/16:1/2:1/128
So you want to go from 1/16, in steps of 1/2, to 1/128. The problem is, while we can understand what you wanted to do, that does not mean that MATLAB can see into your mind.
What does this do in MATLAB?
1/16:1/2:1/128
ans =
1×0 empty double row vector
That is no different than trying the similar operation of:
4:1:0
ans =
1×0 empty double row vector
You can see it must fail, since the first argument is larger than the last, and the step is a positive number.
Were you possibly hoping to create the set: [1/16 1/32 1/64 1/128]? If so, then you could have written the for as the simple:
for hstep = [1/16 1/32 1/64 1/128]
That is nice, because it achieves what you want, and is easy to write, as well as being easy to read. I suppose if you had many steps in that vector, you don't want to write them out explicitly. So as an alternative, you might have tried
for hstep = 2.^[-4:-1:-7]
Or, finally, you might have written it as:
for Numsteps = [16 32 64 128]
hstep = (Xf - Xnum(1))/Numsteps;
Next, do ANY of the above operations really work, exactly as I think you may wish? Your inner loop goes from 1 to 1000 in steps of Numsteps. You wrote:
for k = 1:Numsteps:1000
So, the second serious problem is the inner loop. It looks like what you really wanted to write was:
for k = 1:Numsteps
Thus, you wanted to take Numsteps of the Euler method, and then stop the iteration.
I would suggest you need to think more carefully about how loops work in MATLAB, rather than just assuming MATLAB will know what you meant.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!