Saving all outputs of for for-loop

조회 수: 3 (최근 30일)
Andre Metzger
Andre Metzger 2019년 9월 19일
댓글: Ankit 2019년 9월 20일
I have this code saved in an .m file
function yout=euler1(t0,y0,tfinal,h,f)
y=y0;
for n=t0:0.01:tfinal-h;
y=y+(h.*f(n,y));
end
yout=y
end
and need to save all of the outputs in order to be able to graph it.
How could i modify it in order to save all the outputs at each step/loop to be able to graph it.
  댓글 수: 1
Ankit
Ankit 2019년 9월 20일
Hello Andre,
you asked a similar question and it was answered. Please check the below link. Are you expecting different results?

댓글을 달려면 로그인하십시오.

답변 (1개)

James Tursa
James Tursa 2019년 9월 19일
편집: James Tursa 2019년 9월 19일
Basic steps for you to take would be:
  • Create your range up front, and not as part of the loop indexing. E.g., a t vector
  • Use that range to determine the output variable size, e.g. numel(t)
  • Preallocate the output variable to the size just determined. E.g., y = zeros(something,numel(t))
  • Set the first y value to your initial value. E.g., y(:,1) = y0;
  • Loop on an integer index, e.g. k, that will cover the number of t values
  • Use that index within the loop to calculate your updated values.
For that last step, you would end up with something like this:
for k=1:something
y(:,k+1) = y(:,k) + h * f(t(k),y(:,k));
end
I have used y(:,k) instead of just y(k) to allow for functions that deal with column vectors instead of just scalars.
I have left several details for you to work on. Give it a try and come back to us for more help when you need it.
When you are done, y will contain all of the intermediate values.

카테고리

Help CenterFile Exchange에서 Graphics Performance에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by