code-started simulation: Why can't local variables be accessed by Simulink?

2 次查看(过去 30 天)
I want to use python to run a simulation in SIMULINK. As far as I understand that requires the simulation to be part of a function (not a script). Apparently, using the sim function inside another function means that SIMULINK accesses the base workspace, not the function workspace.
Edit: In the meantime I was able to write variables from the simulation to the caller (function) workspace, using the block "To Workspace" and disabeling the option "Single simulation output" in the model configuration (not sure if this is necessary, I just found that yesterday I was not able to do this and the only change to the options that I remember is this).
I wrote a minimal example of what I'm trying to do:
function test_input()
magic=1;
sim("minimal_input_example_sim.slx");
end
minimal_input_example_sim.slx is (as shown below) just a Constant block with value "magic" and a scope.
The code produces the following error:
Error using test_input
Invalid setting in 'minimal_input_example_sim/Constant' for parameter 'Value'.
Caused by:
Error using test_input
Error evaluating parameter 'Value' in 'minimal_input_example_sim/Constant'
Error using test_input
Not enough input arguments.
If "magic" exists in the base workspace, the simulation runs without error.
I want to give timetables as inputs at inports of the simulation (by using the Dataset type), so this is just the minimal example of the problem.
Now, there is more than one way to solve my problem.
Solution 1: Calling MATLAB functions in python actually creates a base workspace from which SIMULINK can get variables, signals etc. (in other words I am wrong about how the MATLAB engine in python works). With assignin('base',...,...) the variables can be written from the function to the base workspace.
Solution 2: There is a way to make SIMULINK access the function workspace instead of the base workspace (which I was just unable to find).
Maybe you can think of a different solution as well, I'd be happy to hear it.
Cheers,
Claudius

采纳的回答

Claudius Rosendahl
Claudius Rosendahl 2022-9-29
After I played around with the MATLAB engine in python a little more, I came to understand how the workspace works there.
I still cannot access local variables when calling a simulation in a function, but there is a workaround.
function [blub,tout]=test_input()
assignin('base','magic',2);
sim("C:\Users\ClaudiusRosendahl\Desktop\digital_twin_simulation\model\minimal_input_example_sim.slx");
end
When you have a constant block of the value "magic" you can assign a value to magic in the base workspace by using assignin as shown above. This also works when calling the function from python.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Call Python from MATLAB 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by