MATLAB: How can i pass an index to ode function

odeode45

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

Best Answer

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