Any way to get Matlab to execute a command, if a script runs into an error and terminates?
68 views (last 30 days)
Is there a way to get Matlab to execute a command (e.g. send me an email), if it should run into an error and terminate when running some code?
Bonus: It would be helpful if this could be set up directly in the script, rather than being a Matlab setting as such, since because I don't want to notified by an mail every time an error occurs in Matlab - just when I am running certain long scripts.
This would be immensely helpful - since our analysis takes so long to run, we typically leave it running over-night/over the day, and come back at the end to check out the results. If I could set my script up so that Matlab sends me an email (I already know the email-sending bit) if it runs into an error, then I'd be able to remote-desktop in and sort it wherever I am.
Jason Ross on 18 Oct 2012
Edited: Jason Ross on 27 Nov 2018
I largely concur with the try/catch approach already suggested by others. There is functionality built into the Parallel Computing Toolbox and MATLAB Job Server that will let you set callbacks for the state of your job, and also functionality built into the desktop to monitor job progress.
You could, for example, write a callback function that would check the state of your job when it completed and email you if an error was encountered while the job was running.
This would requre that you set up a cluster and use the Parallel Computing Toolbox to make it work -- which may or may not be something you have access to or want to get into if the already suggested solutions will meet your needs.
The following three links provide a basic sketch of what you would need to do -- establish the callback (the code that would send mail), how to submit your script to the cluster (batch), and then the properties you would query in your callback (job state is failed).
The job monitor allows you to monitor activity on your cluster in a GUI:
More Answers (2)
Image Analyst on 18 Oct 2012
Edited: Image Analyst on 18 Oct 2012
Yes. Just use try catch:
% your script which can fail....
% An error will put you here.
errorMessage = sprintf('Error in myScrip.m.\nThe error reported by MATLAB is:\n\n%s', ME.message);
% Run other code or use the system() command to run other programs...
Let me know if you need demo code for how to send email, but there is demo code in the help for sendmail() and setpref().
% Here's where we actually send out the e-mail with the file attached.
sendmail(recipientsEMail, subjectLine, messageBody, attachedFullFileName)
Sean de Wolski on 18 Oct 2012
Edited: Sean de Wolski on 18 Oct 2012