Mostafa
Mostafa

Reputation: 219

Setting a condition on MATLAB ode45 output (while running)

I'm solving a system of ODEs with ode45 for many different parameters(these parameters are coefficients of differential equations) , and I want to find parameters for which the solution is smaller (not larger) than a given value.

How can I set a condition on ode45 , to "detect" automatically if the solution (for some of those parameters) gets larger than that (given) value while solving the system and stop solving for further steps?

Jan suggested to put the following condition in the definition of the input function so the int. I tried this, but it doesn't work: after a few steps (and although the condition is not correct yet) iteration ends soon with the output kept constant at some number. (an incorrect output)

(qm , U , V , etc are constants and X has 4 columns )

[T,X]=ode45(@acceleration,tspan,x0);


function xprime=acceleration(T,X)
   size_X=length(X);
    xprime=zeros (4,1);
        if X(size_X,1)>threshold

  xprime(1)=0;
  xprime(2)=0;
  xprime(3)=0;
  xprime(4)=0;

        else

  xprime(1)=X(3);
  xprime(2)=X(4);
  xprime(3)=X(1)*X(4)^2 - 2*qm*(U+V*(cos(w*T)))*F1(num,X(1),X(2));
  xprime(4)= -2*X(3)*X(4)/X(1) - qm*((U+V*(cos(w*T)))/(X(1)))*F2(num,X(1),X(2));

        end
  end

Upvotes: 2

Views: 1116

Answers (2)

janh
janh

Reputation: 2096

Are you solving a set of equations or trying to integrate over time? Without more info it sounds like you should be using fsolve or fmincon?

If you really are integrating, I think you can use the Events functionality to indicate to ode45 that you want to stop. The ballode example might be helpful.

Upvotes: 0

Jan
Jan

Reputation: 5162

I don't see built in options in the Matlab ODE solvers that may be (mis)used for your purposes.

But you can modify your right hand side in y' = f(t,y) accordingly. I may think of

  • IF y > threshold THEN f(t,y) = 0 -- this should lead to a fast end of the iteration because of the step size control in ODE45
  • Or raising an exception, that only cancels current the iteration (Not sure how to do this ;)

Upvotes: 1

Related Questions