In Modelica I want to implement a function
called clip
that works similiar to Clip
in the Wolfram Language. That is the function will take a list of values x
and return a vector y
of the same length where for each component we have a piecewise function:
y_i := x_i for min ≤ x_i ≤ max, v_min for x_i < min, and v_max for x_i > max
So we should see the following results:
clip( {-3,-2,-1,0,1,2,3} , {-2,2} ) // { -2, -2, -1, 0, 1, 2, 2 }
clip( {-3,-2,-1,0,1,2,3} , {-2,2}, {-10,10} ) // { -10, -2, -1, 0, 1, 2, 10 }
clip( {-3,-2,-1,0,1,2,3} ) // { -1, -1, -1, 0, 1, 1, 1 }
My approach is the following:
function clip "Clip values so they do not extend beyond a given interval"
input Real x[:] "List of values to be clipped";
input Real[2] x_range := {-1, 1} "Original range [min,max] given as a list (default = {-1,1})";
input Real[2] extremes := x_range "Extreme values [v_min, v_max] given as a list (default {min,max})";
output Real y[size(x, 1)] "Clipped values";
protected
Integer n := size(x, 1) "Length of the input vector x";
algorithm
for i in 1:n loop
y[i] := if x[i] < x_range[1] then extremes[1] elseif x[i] > x_range[2] then extremes[2] else x[i];
end for;
end clip;
Note, that here the default expression for extremes
references the input x_range
which itself has the default expression {-1, 1}
.
Unfortunately, I am getting wrong results in Wolfram SystemModeler 12.0 and in OpenModelica (OMEdit v.1.13.2) it won't even compile.
My questions are:
- Is the above function legal Modelica code according to specs?
- Regardless of (1.) is there another way to do this?
https://specification.modelica.org/master/Ch12.html#positional-or-named-input-arguments-of-functions