Main Content

Redirect MATLAB Command Window Output to Java

Output to MATLAB Command Window

MATLAB® displays error messages and the output from functions that are not terminated with a semicolon in the MATLAB command window. You can redirect this output to Java® using a java.io.StringWriter. The MatlabEngine feval, fevalAsync, eval, and evalAsync methods support the use of output streams to redirect MATLAB output.

Redirect MATLAB Output

The MATLAB whos command displays information about the current workspace variables in the MATLAB command window. Use a StringWriter to stream this output to Java.

import  com.mathworks.engine.*;
import java.io.*;

public class RedirectOutput {
    public static void main(String[] args) throws Exception {
        MatlabEngine engine = MatlabEngine.startMatlab();
        // Evaluate expressions that create variables
        eng.evalAsync("[X,Y] = meshgrid(-2:.2:2);");
        eng.evalAsync("Z = X.*exp(-X.^2 - Y.^2);");
        // Get the output of the whos command
        StringWriter writer = new StringWriter();
        eng.eval("whos", writer, null);
        System.out.println(writer.toString());
        writer.close();
        eng.close();
    }
}

Redirect MATLAB Error Messages to Java

This example code attempts to evaluate a MATLAB statement that has a syntax error (unbalanced single quotation marks). Entering this statement in MATLAB causes an error:

disp('Hello'')

MATLAB returns this error message in the command window:

 disp('Hello'')
      ↑
Error: Character vector is not terminated properly.

To redirect this error message to Java, use a StringWriter with the eval method. Catch the MatlatSyntaxException exception thrown by the error and write the MATLAB error message to Java.

import  com.mathworks.engine.*;
import java.io.*;

public class javaRedirectOut {
    public static void main(String[] args) throws Exception {
        MatlabEngine engine = MatlabEngine.startMatlab();
        StringWriter writer = new StringWriter();
        try {
            eng.eval("disp('Hello'')", null, writer);
        } catch (MatlabSyntaxException e) {
            System.out.println("Error redirected to Java: ");
            System.out.println(writer.toString());
        }
        writer.close();
        eng.close();
    }
}

Related Topics