Functions in Modelica
Functions are central in Modelica. We’ll learn about functions with a few different examples.
function plus
input Integer a;
input Integer b;
output Integer result;
algorithm
result := a + b;
end plus;
function plusPlus
input Integer a;
input Integer b;
input Integer c;
output Integer result;
algorithm
result := a + b + c;
end plusPlus;
model Main
Integer res1, res2;
equation
res1 = plus(1, 2);
res2 = plusPlus(1, 2, 3);
algorithm
Modelica.Utilities.Streams.print("1+2 = " + String(res1));
Modelica.Utilities.Streams.print("1+2+3 = " + String(res2));
end Main;
Here’s a function that takes two Integer
s and returns their sum as an Integer
.
Modelica requires explicit algorithm sections in functions, where the actual computations are performed.
When you have multiple input parameters, you need to declare each of them separately with the input
keyword.
To use functions in Modelica, you typically call them within a model or another function. Here, we’re using them in a Main
model.
Call a function just as you’d expect, with name(args)
.
To run this Modelica code, you would typically use a Modelica simulation environment. The output would be:
1+2 = 3
1+2+3 = 6
There are several other features to Modelica functions. One is the ability to have multiple output parameters, which we’ll look at next.