Access array elements from string argument in Modelica

时间:2015-11-12 11:07:40

标签: arrays modelica

I'm having a task in Modelica, where within a function, I want to read out values of a record (parameters) according to a given string type argument, similar to the dictionary type in Python.

For example I have a record containing coefficicents for different media, I want to read out the coefficients for methane, so my argument is the string "Methane".

Until now I solve this by presenting a second array in my coefficients-record storing the names of the media in strings. This array I parse in a for loop to match the requested media-name and then access the coefficients-array by using the found index.

This is obviously very complicated and leads to a lot of confusing code and nested for loops. Isn't there a more convenient way like the one Python presents with its dictionary type, where a string is directly linked to a value?

Thanks for the help!

1 个答案:

答案 0 :(得分:3)

您可以使用几种不同的替代方案。我将添加我最喜欢的模式:

model M
  function index
    input String[:] keys;
    input String key;
    output Integer i;
  algorithm
    i := Modelica.Math.BooleanVectors.firstTrueIndex({k == key for k in keys});
  end index;
  constant String[3] keys = {"A","B","C"};
  Real[size(keys,1)] values = {1,2*time,3};
  Real c = values[index(keys,"B")] "Coefficient";
  annotation(uses(Modelica(version="3.2.1")));
end M;

我喜欢这段代码的原因是因为它可以通过Modelica编译器提高效率。您可以创建键向量和相应的数据向量。它不是记录的原因是你希望键向量是常量,并且值可能随时间变化(对于比你想要的更通用的字典)。

然后,编译器可以为要从中查找的任何常量名称创建常量索引。这使得编译器中的排序和匹配更好(因为没有未知索引)。如果您想在运行时查找密钥,则代码也适用于此。