Thursday, June 11, 2015
Three Ways to Call A Simple "Hello World" Java Program in MATLAB
---------------------------
###Installation Environment
Environment
```
Ubuntu 12.04, 64-bit
Matlab R2012a, 64-bit
```
---------------------------
###Install Package
Install open JDK and check the version
```bash
$ sudo apt-get install openjdk-6-jdk
$ sudo apt-get install openjdk-6-jre
$ javac -version
$ java -version
```
A simple HelloWorld.java code
```java
public class HelloWorld {
public static void main( String args[] )
{
System.out.println( "Hello World!" );
}
}
```
---------------------------
### The First Way
Compile and run HelloWorld
```bash
$ javac -cp %CLASSPATH:/path/to/matlab/jre HelloWorld.java
$ jar -cvf library.jar HelloWorld.class
```
Example1.m
```matlab
>> clear all;
>> javaaddpath(/path/to/library.jar);
>> HelloWorld
```
---------------------------
### The Second Way
Compile and run HelloWorld
```bash
$ javac HelloWorld.java # This will produce a HelloWorld.class file
$ java HelloWorld
```
Example2.m
```matlab
>> java -version % consistent with the java version installed in system
>> which classpath.txt % add the path HelloWorld.class to the end of classpath.txt
>> javaaddpath(/path/to/matlab/HelloWorld.class);
>> o = HelloWorld;
>> javaMethod('main', o);
```
---------------------------
### The Third Way
Compile and run HelloWorld
```bash
$ javac HelloWorld.java # This will produce a HelloWorld.class file
$ java HelloWorld
```
Example3.m
```matlab
>> java -version % consistent with the java version installed in system
>> which classpath.txt % add the path HelloWorld.class to the end of classpath.txt
/usr/local/MATLAB/R2012a/toolbox/local/classpath.txt
>> o = HelloWorld;
>> javaMethod('main', o, '');
```
---------------------------
Reference:
http://www.mathworks.com/matlabcentral/answers/99993-how-do-i-call-a-simple-hello-world-java-program-in-matlab
https://sergiolima.wordpress.com/2009/10/15/using-java-objects-with-matlab/
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment