Search code examples
matrixmatrix-multiplicationmodelicaopenmodelica

Matrix multiplication in Open Modelica


I've made a simple model and dosen't seem to work. I get this errors: "Too many equations, over-determined system. The model has 6 equation(s) and 2 variable(s)" and sum_vs = sum_vs + v[1] * A[1,1] has size 1 but 0 variables ().

I've been staring at this code all morning, it is a simple example because I want to make it more complicated in the future (bigger dimensions). This is the code:

model MatrixMultiplication
parameter Real A[2,2]=[1,2;1,2];
parameter Real v[2]={1,2};
parameter Real sum_vs=0; //counter
Real vs[2];
equation
for i in 1:2 loop
  for j in 1:2 loop
     sum_vs = sum_vs + v[j] * A[i,j];
  end for;
  vs[i]=sum_vs;
end for;
end MatrixMultiplication;

The ideal result is vs[1,2]=A[2,2]*v[2];

Thanks!


Solution

  • The equation you have defined is fundamentally flawed, i.e. sum_vs = sum_vs + v[j] * A[i,j]; is simply not a valid equation. What you are writing is an assignment not an equation, see e.g. https://mbe.modelica.university/behavior/equations/equations/ to understand what an equation is in Modelica. You need to make sure to understand the concept of balanced models in which the number of equations and unknowns need to be the same.

    Additionally errors are:

    • Assigning a value to sum_vs in its declaration will not allow you to define an additional equation
    • The value of a parameter cannot be changed in the equation section, as it is constant for the time of the simulation and values in the equation can change.

    If you want to do that kind of "programming" in Modelica (which is generally not recommended for various reasons), you need to define an algorithm- not an equation-section. Your example re-built to work as an algorithm would look like (not sure if it gives the result you expect, because I don't understand the "ideal result" equation):

    model MatrixMultiplication
      parameter Real A[2,2]=[1,2;1,2];
      parameter Real v[2]={1,2};
      Real sum_vs;
      Real vs[2];
    
    algorithm 
      for i in 1:2 loop
        for j in 1:2 loop
           sum_vs :=sum_vs + v[j]*A[i, j];
        end for;
        vs[i]:=sum_vs;
      end for;
    end MatrixMultiplication;
    

    Regarding the difference between algorithm and equation sections, e.g. read Difference between equation and algorithm section.

    A valid equation could be defined by the following code:

    model MatrixMultiplication
      parameter Real A[2,2]=[1,2;1,2];
      parameter Real v[2]={1,2};
      Real vs[2];
    
    equation 
      vs = A * v;
    end MatrixMultiplication;
    

    Again, I'm not sure this is what you want to compute. But at least it is a valid equation.