How to call Octave from Java

If you need to perform sophisticated numerical mathematics or data analysis in Java, you may consider offloading some of needed computation to Octave program, which is equipped with extensive libraries of numerical, statistical and graphics algorithms.

Then the question is how can you interface with an external Octave program from within Java?

One straightforward way is to call an external Octave script from Java, and use standard input/output streams (stdin/stdout) to handle parameter passing and output retrieval. However, data passing via stdin/stdout tends to be rather slow in Octave. Thus if the size of input parameters and output result is significant, using stdin/stdout will unnecessarily slow down your Java program.

A better approach to run Octave inside a Java application is to use JavaOctave, an open-source Java interface for Octave.

To use JavaOctave, download JavaOctave library, and include it in your Java program.

Here is a code example of running Octave inside a Java program using JavaOctave. It shows two different ways to instantiate a matrix and send it to Octave from within Java. It also illustrates how you can retrieve Octave output back to Java.

import dk.ange.octave.OctaveEngine;
import dk.ange.octave.OctaveEngineFactory;
import dk.ange.octave.type.OctaveDouble;

OctaveEngine octave = new OctaveEngineFactory().getScriptEngine();
OctaveDouble matA = new OctaveDouble(new double[] {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}, 3, 5);
octave.put("a", matA);
octave.eval("a");

String matB = "b = [1,2,3; 4,5,6; 7,8,9]";
octave.eval(matB);

octave.eval("x = b(1,:)");
OctaveDouble varX = (OctaveDouble) octave.get("x");
System.out.println("Result: "+varX.get(1)+" "+varX.get(2)+" "+varX.get(3));
octave.close();
a =

    1    4    7   10   13
    2    5    8   11   14
    3    6    9   12   15

b =

   1   2   3
   4   5   6
   7   8   9

Result: 1.0 2.0 3.0

Subscribe to Xmodulo

Do you want to receive Linux FAQs, detailed tutorials and tips published at Xmodulo? Enter your email address below, and we will deliver our Linux posts straight to your email box, for free. Delivery powered by Google Feedburner.


Support Xmodulo

Did you find this tutorial helpful? Then please be generous and support Xmodulo!

The following two tabs change content below.
Dan Nanni is the founder and also a regular contributor of Xmodulo.com. He is a Linux/FOSS enthusiast who loves to get his hands dirty with his Linux box. He likes to procrastinate when he is supposed to be busy and productive. When he is otherwise free, he likes to watch movies and shop for the coolest gadgets.

Leave a comment

Your email address will not be published. Required fields are marked *