Using MATLAB inside the Engee Function block
In this example, we will look at how to apply code inserts in MATLAB inside the Engee Function block. To do this, we use persistent variables, which allow us to expand the functionality of the MATLAB code and store the values in themselves even after exiting the function.
For this demonstration, we wrote a counter function in MATLAB, which is reset if the input value is 1.
The function code is shown below.
Next, we will test the operation of this function. To do this, connect MATLAB and go to the folder with the function.
using MATLAB
mat"cd $(@__DIR__)"
mat"cnt(0)"
mat"cnt(0)"
mat"cnt(0)"
mat"cnt(1)"
As we can see, the function works correctly every time we call it. With the parameter rst=0, the counter increases, and with rst=1 it is reset.
Now that we have tested the function itself, we will add an auxiliary function to run the model and create a model in which we will apply this counter.
# Подключение вспомогательной функции запуска модели.
function run_model( name_model)
Path = (@__DIR__) * "/" * name_model * ".engee"
if name_model in [m.name for m in engee.get_all_models()] # Проверка условия загрузки модели в ядро
model = engee.open( name_model ) # Открыть модель
model_output = engee.run( model, verbose=true ); # Запустить модель
else
model = engee.load( Path, force=true ) # Загрузить модель
model_output = engee.run( model, verbose=true ); # Запустить модель
engee.close( name_model, force=true ); # Закрыть модель
end
sleep(5)
return model_output
end
The figure below shows the model we have developed.
Now let's analyze the code presented in the Engee Function block.
So, the sequence of actions is: connect the MATLAB library, then explicitly specify the path to our counter file and call it, feeding the result to the block output.
Now let's describe the loop in which we will call our model. In it, the counter will be reset on the first and third runs of the model.
rst = 0;
for i in 1:1:5
if i == 1 || i == 3
rst = 1;
else
rst = 0;
end
run_model("MATLAB_in_Engee_models") # Запуск модели.
c = collect(Cnt)
print("Значение счётчика на "*string(i)*" запуске модели: "*string(c.value))
end
As a result, our function works correctly: in those runs when we set "rst=1", the counter is zero.
Conclusion
We figured out how to use MATLAB code inserts in the Engee Function block, and also demonstrated the ability to connect MATLAB files to the Engee Function. As you can see, these functions are easy to use, and they work correctly.