Search code examples
matlabfor-loopode

How to write a program to call a differential equation 50 times using FOR loop in MATLAB using ode23s?


I need two solve two differential equations depending upon the different values of vin 50 times. My code is written as:

for i=1:1
[T,Y]=ode23s(@(T,X)sys(T,X,vin),[t0 .00025],X(:,1)) 
vin =-12;
[T1,Y1]=ode23s(@(T,X)sys(T,X,vin),[.00025 .0005],Y(end,:))
vin=12
[T2,Y2]=ode23s(@(T,X)sys(T,X,vin),[.0005 .00075],Y1(end,:))
vin=-12
[T3,Y3]=ode23s(@(T,X)sys(T,X,vin),[.00075 .001],Y2(end,:))
end
Tf=[T;T1;T2;T3];
Xf=[Y;Y1;Y2;Y3];

Now I need to do this for 100 cycles that is upto Y50 and T50 using for loop How do I do that?


Solution

  • odextend applied to a solution structure (the last variant of the solver call in the documentation) takes the last state and the new equation and extends the solution structure using the same solver to the new end time.

    So doing

    T=linspace(0,0.025,101); 
    vin = 12
    sol = ode23s(@(T,X)sys(T,X,vin),[T(1) T(2)],X0); 
    for k=2:100
      vin = -vin
      sol = odextend(sol,@(T,X)sys(T,X,vin),T(k+1));  
    end
    

    should work, my octave version does unfortunately not have odextend to test for syntactical correctness.

    The solution can be evaluated via the contained samples and the dense output

    Tsmooth = linspace(0,0.025,2001)
    Ysmooth = deval(sol,Tsmooth)
    
    hold on;
    plot(Tsmooth, Ysmooth(:,1), '-b');
    plot(sol.x, sol.y(:,1), '+r');
    hold off;