How can i pass an index to ode function?
조회 수: 5 (최근 30일)
이전 댓글 표시
Hi all,
I'm a new user and I'm having trouble with ode45 function for a second order differential equation.
I should find a soultion for the problem d2y/dt2=(1-A*y)dy/dt-y in which A is a vector that depends on the time. I use [t,f]=ode45('fun',t,y0); How can I tell to the software that at timestep 1 I should use A(1) or a timestep 2 I should use A(2)?
thank you in advance Francesco
thank u advance
댓글 수: 0
채택된 답변
Star Strider
2014년 4월 24일
I defined ‘A’ as a large-amplitude random vector to be sure it worked:
A = randi(50,1,5)-1; % Create ‘A’
fun = @(t,y,A) [y(2); (1 - y(1) - A.*y(2))];
ti = 0:0.01:0.09; % Incremental time vector
te = 0; % Initial value for ‘t(end)’
ye = eps*[1 1]; % Initial ‘initial conditions’ vector
tv = []; % Initialise ‘tv’ to accumulate ‘t’
yv = []; % Initialise ‘yv’ to accumulate ‘y’
for k1 = 1:size(A,2)
t = te + ti; % Increment ‘t’ for this iteration
a = A(k1); % Select new value for ‘A’
[t, y] = ode45(@(t,y)fun(t,y,a), t, ye);
te = t(end);
ye = y(end,:); % Becomes new initial conditions
tv = [tv; t]; % Add current run to previous ‘tv’ vector
yv = [yv; y]; % Add current run to previous ‘yv’ matrix
end
figure(1)
plot(tv, yv)
legend('Y_1', 'Y_2', 'Location', 'NW')
xlabel('T')
grid
댓글 수: 6
Star Strider
2014년 5월 7일
I can’t run your code because there are too many undefined variables (from A to Ex). Since the first call to ode45 seems to be throwing the error, I suggest you insert:
IC_xe = xe % Check initial condition vector ‘xe’
just before your initial call to ode45 (the one that calls fun). That will write the value of xe to the Command Window, and tell you what xe is.
It might be necessary to insert a similar line before the second call (the one that calls fun1) in case that throws a similar error. That way you’ll know what is being passed to ode45 in the following line.
추가 답변 (2개)
Sara
2014년 4월 24일
You will need check the time into the fun and pass both A and t to it. You want something like:
[t,f]=ode45(@(t,x)fun(t,x,t,A),t,y0);
function dy = fun(t,x,timeserie,A)
k = find(t >= timeserie,1);
k = max(1,k-1);
a = A(k);
댓글 수: 0
Jan
2014년 4월 25일
It is important, that the function to be integrated is smooth. Otherwise the result of the integration is suspicious. See http://www.mathworks.com/matlabcentral/answers/59582#answer_72047
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Ordinary Differential Equations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!