Saving each vector of an ode45 vector solution in a matrix.

조회 수: 6 (최근 30일)
Gabriel Venter
Gabriel Venter 2021년 4월 26일
댓글: J. Alex Lee 2021년 4월 27일
I have the following code, where I am using a different value of a parameter G in my ODE system (solving it w/ ode45) and want to plot each solution on the same graph. It isnt the same as IC's, as these are the same but the parameter varies. Currently I have:
for i=1:20
G=i/20 %Saving that iterates value of G
[phi,y]=ode45(@(phi,y) odefun(phi,y,G), timerange, IC);
z(i,;)=y %
end
then I want to save all these y's without creating 20 vectors. Is there a way to save each vector y as a column of a matrix? I am very lost and any direction would be very helpful, I cannot find a thread or anythign on the helpcenter.
Thanks in advance
  댓글 수: 3
J. Alex Lee
J. Alex Lee 2021년 4월 27일
Another important question is if "timerange" are just the 2 point limits of time, or a vector; if just the limits, each version may produce different length of y (even if it was 1D problem). In such a case, you couldn't [easily] use a matrix to store the results anyway.
Gabriel Venter
Gabriel Venter 2021년 4월 27일
I have a 2D autuonomous ODE system here. And I was worried about this timestep problem since ode45 uses a variable timestep and that would be different for different G, so clearly what I was doing was stupid. Thanks!

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

답변 (1개)

J. Alex Lee
J. Alex Lee 2021년 4월 27일
편집: J. Alex Lee 2021년 4월 27일
Use a cell array instead
z = cell(1,20)
for i=1:20
G=i/20 %Saving that iterates value of G
[phi,y]=ode45(@(phi,y) odefun(phi,y,G), timerange, IC);
z{i}=y %
end
Or better yet just use the solution structure version of output
for i=20:-1:1
G=i/20 %Saving that iterates value of G
sol(i) = ode45(@(phi,y) odefun(phi,y,G), timerange, IC);
end
  댓글 수: 2
Gabriel Venter
Gabriel Venter 2021년 4월 27일
Thank you! Lifesaver. What does the extra "20:-1:1" bit mean there, and why is it in that last loop but not the first?
J. Alex Lee
J. Alex Lee 2021년 4월 27일
glad it helped!
"20:-1:1" is going backwards, so the pre-allocation of the structure array is implied. Didn't need to do it with the cell array version since it was straightforward to pre-allocate an empty cell array. You could loop backward on that example as well, and wouldn't need to do the explicit pre-allocation.

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

카테고리

Help CenterFile Exchange에서 Ordinary Differential Equations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by