Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try … finally equivalent in Matlab [duplicate]

Possible Duplicate:
How do you handle resources in MATLAB in an exception safe manner? (like “try … finally”)

I use Matlab parallel computing toolbox this way:

matlabpool open 

parfor …

matlabpool close

If error occurs in parfor, the program is terminated, and matlabpool is not closed. When I fix the bug and run it again, matlabpool open fails because it is already open. So I need to close it manually, which I always forget. The ideal way would be to change it to (pseudo-code):

matlabpool open 
try
  parfor …
finally
  matlabpool close
end

Is there any best practice for this?

like image 406
Roman Shapovalov Avatar asked Jan 26 '12 16:01

Roman Shapovalov


People also ask

What is try catch MATLAB?

If you use try and catch , this code catches any exception and repackages it as a warning, allowing MATLAB to continue executing subsequent commands.

How do you check for errors in MATLAB?

Select MATLAB > Code Analyzer, and then select the Enable integrated warning and error messages check box. Set the Underlining option to Underline warnings and errors . When continuous code checking is enabled, MATLAB displays warning and error messages about your code in the Editor and Live Editor.


1 Answers

Use onCleanup. It'll let you set up code that'll get executed when you exit the scope, regardless of a normal or a error exit. So it works like finally, plus it quashes exceptions in the cleanup, and all onCleanups are independent.

function doSomething
matlabpool open
cleaner = onCleanup(@() matlabpool('close'));
parfor ...
%// and then no need to call close here

You need to change the try...finally to a function, or stick it inside one, for this to work right. The cleanup code only gets executed with the GC clears the contents of cleaner, which happens when its workspace goes out of scope when you leave the function (or when you manually clear it). Unlike some other languages, Matlab's try block is not a lexical scope for variables; variables assigned for the first time inside a try will stick around until their enclosing function is left. Same for all other blocks: the function is the only level of scoping for local variable lifetimes.

like image 200
Andrew Janke Avatar answered Sep 22 '22 19:09

Andrew Janke