Search code examples
modelica

Modelica - iterator with exception?


Slightly generalised example:

How do I make a for loop with exceptions when I define model equations?

The following works:

  model Test
     Real[9] q;
  equation
     q[2] = 1.2;
     q[4] = 1.4; 
     for i in {1,3,5,6,7,8,9} loop
        q[i] = 0;
     end for;
  end Test;

But I would rather like to write something like:

  model Test
     Real[9] q;
  equation
     q[2] = 1.2;
     q[4] = 1.4;
     for i in 1:9 and not in {2,4} loop
        q[i] = 0;
     end for;
  end Test;

Is this possible?


Solution

  • This should be possible, as long as you make sure to have an equation for every unknown.

    Probably not the perfect solution, but actually pretty readable:

    model LoopException
      Real[9] q;
    equation 
      q[2] = 1.2;
      q[4] = 1.4; 
      for i in 1:9 loop
        if Modelica.Math.Vectors.find(i, {2, 4}) == 0 then
          q[i] = 0;
        end if;
      end for;
    end LoopException;
    

    As an alternative, you could also try to write an "Array Constructor with Iterators" (Modelica Language Spec. Sec. 10.4.1), but that probably gets a bit messy...