I have the following code to execute:

$X$ = [0;0;0;0]; $sw$ = 0;

for k = 1 : n
    if (sw(k) == 0 && X(2,k)> 0.7 ) || (sw(k) == 1 && X(1,k) >0)
        sw(k+1) = 1;
        X(:,k+1) = X(:,k) +h*(A1*X(:,k) + B1*u);
        sw(k+1) =0;
        X(:,k+1) = X(:,k) +h*(A*X(:,k) + B*u);


This is fine. I wanted to solve the same ODE using the bulit-in ode suite. How do I check for $sw$ and $X$ after each iteration to see which one of the two equations to solve.

  • 1
    $\begingroup$ Welcome to SciComp.SE! It would help if you actually wrote down (using LaTeX/MathJax) the ODE you are trying to solve. You should also look at the odeset documentation in Matlab (especially about Events). But be aware that pure "how do I use this function in Matlab" questions are off-topic here, and better asked at Matlab Answers. (Your question is borderline, depending on how you edit it.) $\endgroup$ Aug 28, 2016 at 20:21

1 Answer 1


You can use the "event location" feature of MATLAB's ODE suite to integrate the system of equations in one of the two states and stop the integration when the condition has been reached for a state change. You can then restart the integration in the other state and setup an event trigger to stop the integration at the next state change. See



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.