Home > Blockchain >  Equation in if branch is not executed
Equation in if branch is not executed

Time:11-01

I have a question that confused me for a long time. As you know, when we use an if condition in Modelica, that means if the expression is true, then Modelica will do the corresponding equation. But when i test the following code, I am confused:

model Model134
  Real a(start = 0);
equation 
  if not sample(0, 2) then 
    a = 1;
  else
    a = 3;
  end if;
end Model134;

I think a will be changed every 2s (start time=0), but when I simulate this model, it dose not change and a is equal to 1 all the time.

Dose anybody know the root cause?

CodePudding user response:

a does change its value, but you don't see it in the plot.

sample(0, 2) creates a time event every 2 seconds. The return value of sample() is only true during the event. So the value of a changes, but after the event it immediately changes back.

To proof that a really does change its value you can use this code for example:

model Model134
  import Modelica.Utilities.Streams.print;
  Real a;
equation 
  if sample(0, 2) then
    a = 1;
  else
    a = 0;
  end if;

  when a > 0.5 then
    print("a is "   String(a)   " at t="   String(time)   "s");
  end when;
  annotation (experiment(StopTime=10));
end Model134;

You should see something like this in the simulation log:

a is 1 at t=2s
a is 1 at t=4s
a is 1 at t=6s
a is 1 at t=8s
a is 1 at t=10s

See also enter image description here

This is the plot simulated when trying your above code in OpenModelica with settings shown in the second figure.

enter image description here

A time event is triggered when sample(startTime,interval) evaluates true at every multiple of 2 seconds and based on your code logic this should activate else
block and assign value of variable a to be 3.

  • Related