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:

  1. We create an array a that will hold exactly 5 integers. By default, an array is initialized with zeros.

  2. We can set a value at an index using the array[index] = value syntax, and get a value with array[index].

  3. The size function returns the length of an array along a specified dimension.

  4. We can declare and initialize an array in one line, as shown with arrays b and c.

  5. Modelica supports multi-dimensional arrays. We demonstrate this with the twoD array.

  6. We use the fill function to initialize an array with a specific value.

  7. The String function is used to convert arrays to strings for printing.

  8. 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.