How to run a Matlab script asynchronously from a Matlab app?
22 vues (au cours des 30 derniers jours)
I currently have an app that has a button that is supposed to start and stop another matlab script. The other Matlab script is supposed to run until the button in the app is pushed again.
The app's logic looks roughly like this:
function StartDataCollectionButtonPushed(app, event)
% app.experiment_running is a public variable
if(app.experiment_running == false)
% Change state of app to indicate experiment is running
app.experiment_running = true;
app.StartDataCollectionButton.BackgroundColor = [1 0 0];
app.StartDataCollectionButton.Text = "Stop Data Collection";
% Placeholder value, assume this is a valid file path.
% Change state of app to indicate no experiment is running
app.experiment_running = false;
app.StartDataCollectionButton.BackgroundColor = [0 1 0];
app.StartDataCollectionButton.Text = "Start Data Collection";
% Need way of quitting Matlab_File.m
And the external Matlab_File.m looks like this:
z = 0;
% This counter is here so that the script will eventually quit on its own if I cannot stop it
z = z+1
if z >= 1e5
The problem is that run("Matlab_File.m") is a blocking call, so even if I click on the "StartDataCollectionButton" as Matlab_File.m is executing, experiment_running isn't set to false until Matlab_File.m returns on its own. I'd like to be able to change that flag in the middle of Matlab_File's execution and have it exit the loop and return.
Jon le 18 Avr 2022
One way would be to use a MATLAB timer and make your script that you want to execute asynchonously be the timer's callback function. Note that if this script is to execute repeatedly you can set up the timer for periodic execution (rather than using a loop)
Please see this link for general info on setting up timers and timer functions: https://www.mathworks.com/help/matlab/matlab_prog/use-a-matlab-timer-object.html
Timers have a stop function that could be called when you push the button to stop the test.
If there is some cleanup that must be done when the timer stops you can also provide the timer with a stop callback function to perform those steps.
Plus de réponses (1)
Bruno Luong le 20 Avr 2022
Modifié(e) : Bruno Luong le 20 Avr 2022
@Jan Bartels "The problem is that run("Matlab_File.m") is a blocking call, so even if I click on the "StartDataCollectionButton" as Matlab_File.m is executing, experiment_running isn't set to false until Matlab_File.m returns on its own."
I have implemented the same pattern and I don't think it's true, Callback is even driven. You have to make sure the properties 'Interruptible' is set to 'on' and 'BusyAction' to 'queue'. When you click it will change, you might add 'redraw' statement at the end of the callback and before the check in your script so that the event is correctly broadcasted and arrived.
You might add some code to protect with user click twice and the script have some latency to capture the stop event or such.