MATLAB: How to redirect MATLAB Engine errors to a file on Linux

descriptordupdup2engopenengoutputbufferfilefilenoMATLABstderrstderr_filenostreamunix

I would like to redirect all MATLAB error messages in my application that uses the MATLAB Engine to a file.

Best Answer

The following example is a modified version of the engdemo.c example from the MATLAB documentation.
The changes in order to redirect the errors from MATLAB Engine are:
1. Create a new file descriptor for the error output file.
2. Temporarily redirect the standard error stream to the output file.
3. Start the MATLAB Engine using engOpen().
4. Redirect standard error back to the original file descriptor.
When the engOpen() function starts a new MATLAB process, the new process will inherit stderr that is in effect at the time of the engOpen() call. After the engine is opened, the original application can redirect its own stderr back to its original setting. From that point forward, the application and the MATLAB process will use separate output streams.