Last updated on June 5, 2020 by Dan Nanni
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
This website is made possible by minimal ads and your gracious donation via PayPal or credit card
Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.
Xmodulo © 2021 ‒ About ‒ Write for Us ‒ Feed ‒ Powered by DigitalOcean