How to simulate a Simulink model through a .m file, that is executed by a GUI

3 views (last 30 days)
Hi everyone,
I'm new to app designer and have written a code that should execute a m.file that is calling a Simulink Modell. When I execute the m.file by itself, everything works fine. But when I call the m.file through the GUI it skips the Simulink Modell. The Error message I get is
%% relevant Code in GUI
% Button pushed function: AuswertungstartenButton
function AuswertungstartenButtonPushed(app, event)
if app.SettingsCheck
run Kennfeldabhaengigkeit.m;
app.LabelAuswertungStarten.Text = 'Execution started';
app.LabelEingabeSpeichern.Visible = 'on';
else
app.LabelAuswertungStarten.Text = 'Please set needed parameters before!';
app.LabelEingabeSpeichern.Visible = 'on';
end
end
-> in the GUI you have to push a button to call "Kennfeldabhaengigkeit.m"
%% relevant Code in "Kennfeldabhaengigkeit.m"
...
% time variables for Simulink
time_step=20;
time_max=1*time_step;
time_vec=(0:time_max/time_step:time_max)';
....
for i=1:length(nmot_vec)
...
sim Kennfelder_Lamdyn.slx
...
end
-> "Kennfeldabhaengigkeit.m" calls "Kennfelder_Lamdyn.slx"
Solver settings in Simulink
Does anyone know help?

Answers (1)

Fangjun Jiang
Fangjun Jiang on 11 Jan 2023
It is a source workspace issue.
Based on your code, Kennfeldabhaengigkeit.m is a script. "When I execute the m.file by itself", it assigns the variable "time_max" in the base workspace. The model uses "time_max" from the base workspace as "stop_time" and it is able to find "time_max" in the base workspace.
When you execute "run Kennfeldabhaengigkeit.m;" inside function AuswertungstartenButtonPushed(app, event), variable "time_max" is assigned in the function workspace of function AuswertungstartenButtonPushed(app, event). The model can not find the variable "time_max" in the base workspace, thus the error.
If you assign the variable "time_max" in the base workspace first and then you run your app again, this error will disappear but similar error regarding other variables might appear.
Searching for "SrcWorkspace" in "doc sim" page will lead you to the topic. It changed a few times since R2009b, R2017a. You didn't specify your MATLAB version.
The solution is to look at "doc sim" and apply the correct syntax of sim() according to your MATLAB version.

Categories

Find more on Programmatic Model Editing in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!