if-Statements

1 General Description

The semantics of an if-statement is:


if expression then


{ algorithm ";" }


{ elseif expression then


{ algorithm ";" }


}


[ else


{ algorithm ";" }


]


end if;


inside an algorithm section and


if expression then


{ equation ";" }


{ elseif expression then


{ equation ";" }


}


[ else


{ equation ";" }


]


end if;


inside an equation section.


If the condition after the keyword if evaluates to true, the statements after then are executed. Otherwise if there are one or more elseif-parts there conditions are evaluated in order; the first that evaluates to true causes the corresponding statements to be executed. Otherwise, if present, the statements in the else-part are executed. The elseif part is conditional and can appear in zero or more iterations. The else-clause is conditional depending on the variability of the if-expression. In case the expression is of parameter type then the else-clause can be emitted. In case the variability of the expression condition is higher than parameter then the else-clause cann't be omitted since the single assignment rule would not hold, because the number of equations may change during a simualtion.


2 SumVector

In the class SumVector there is an exmple of an if-statement which performs a combined summation and computation on a vector v.



3 Simulation of SumVector

After we have simulated SumVector we see that the sum of the absolute value of the elements in the vecor is 1500.






4 Assignments within if-Statements

There are a special feature regarding assignment statements inside if-statements. Modelica guarantees that all the outputs of an algorithm section always have well-defined values, and that an algorithm section does not have memory of previous invocations. This is achieved by initializing all conditionally assigned variables to their start-values whenever the algorithm is invoked.


4.1 CondAssign

The algorithm section in the class CondAssign below automatically assigns the start values 35 and 45 to the variables x and y respectively when entering the algorithm section since these variables are conditionally assigned within the algorithm section. This means that the condition x>5 becomes 35>5 which is always true. On the other hand, the variable z is not given its start value when entering the algorithm section since it is not conditionally assigned; it is actually an input to the algorithm section.



4.2 Simulation of CondAssign




4.3 CondAssign

The function CondAssignFunc below behaves similarily. Here the local variables x and y are automatically assigned the default initial values 35 and 45 on entry to the algorithm section that comprises its function body.




4.4 Simulation of CondAssignFuncCall