Arrays in Modelica
Our first example demonstrates how to create and work with arrays in Modelica. Arrays are fundamental data structures that store collections of elements of the same type.
model Arrays
Integer[5] a;
Integer[5] b = {1, 2, 3, 4, 5};
Integer[5] c = {100, 0, 0, 400, 500};
Integer[2, 3] twoD;
equation
// Initialize the array 'a' with default values (all zeros)
a = fill(0, 5);
// Set a value at a specific index
a[5] = 100;
// Print the arrays
Modelica.Utilities.Streams.print("emp: " + String(a));
Modelica.Utilities.Streams.print("set: " + String(a));
Modelica.Utilities.Streams.print("get: " + String(a[5]));
// Get the length of an array
Modelica.Utilities.Streams.print("len: " + String(size(a, 1)));
// Print the pre-initialized arrays
Modelica.Utilities.Streams.print("dcl: " + String(b));
Modelica.Utilities.Streams.print("idx: " + String(c));
// Initialize and print a 2D array
for i in 1:2 loop
for j in 1:3 loop
twoD[i, j] = i + j - 2;
end for;
end loop;
Modelica.Utilities.Streams.print("2d: " + String(twoD));
// Re-initialize and print the 2D array
twoD = {{1, 2, 3}, {1, 2, 3}};
Modelica.Utilities.Streams.print("2d: " + String(twoD));
end Arrays;In this Modelica example:
We create an array
athat will hold exactly 5 integers. By default, an array is initialized with zeros.We can set a value at an index using the
array[index] = valuesyntax, and get a value witharray[index].The
sizefunction returns the length of an array along a specified dimension.We can declare and initialize an array in one line, as shown with arrays
bandc.Modelica supports multi-dimensional arrays. We demonstrate this with the
twoDarray.We use the
fillfunction to initialize an array with a specific value.The
Stringfunction is used to convert arrays to strings for printing.Modelica uses 1-based indexing, unlike many other programming languages which use 0-based indexing.
Note that when printed, arrays in Modelica appear in the form {v1, v2, v3, ...}.
To run this model, you would typically use a Modelica simulation environment. The output would look similar to:
emp: {0, 0, 0, 0, 0}
set: {0, 0, 0, 0, 100}
get: 100
len: 5
dcl: {1, 2, 3, 4, 5}
idx: {100, 0, 0, 400, 500}
2d: {{0, 1, 2}, {1, 2, 3}}
2d: {{1, 2, 3}, {1, 2, 3}}This example demonstrates the basics of working with arrays in Modelica, including initialization, accessing elements, and working with multi-dimensional arrays.