I am trying to figure out a way to run a .m file from java.
When the .m file is run it outputs a text file that I need to retrieve. I already have the code to retrieve the text file in java but I still cannot figure out how to start and run the .m file from java so that it outputs the file that I need. Any ideas?
您可以启动一个 Java 进程并运行 matlab..."matlab -r "yourMfile"
Here is the code, you are looking for:
import matlabcontrol.*;
public class matlabconnect
{
public static void main(String[] args)
throws MatlabConnectionException, MatlabInvocationException
{
// create proxy
MatlabProxyFactoryOptions options =
new MatlabProxyFactoryOptions.Builder()
.setUsePreviouslyControlledSession(true)
.build();
MatlabProxyFactory factory = new MatlabProxyFactory(options);
MatlabProxy proxy = factory.getProxy();
// call builtin function
proxy.eval("disp('hello world')");
// call user-defined function (must be on the path)
proxy.feval("matlab_file_name");
// close connection
proxy.disconnect();
}
I have tested the program. It is working well. Do not forget to put your matlab file to its default path.
There is already a bit newer api for matlab / JAVA
<dependency>
<groupId>com.diffplug.matsim</groupId>
<artifactId>matconsolectl</artifactId>
<version>4.5.0</version>
</dependency>
and
// create proxy
MatlabProxyFactoryOptions.Builder builder = new MatlabProxyFactoryOptions.Builder();
MatlabProxyFactory factory = new MatlabProxyFactory(builder.build());
// get the proxy
MatlabProxy proxy = factory.getProxy();
// call user-defined function (must be on the path)
proxy.eval("addpath('"...PATH..."')");
proxy.feval("function");
// close connection
proxy.disconnect();
I think MatlabControl is what you want. It's all described here: http://www.cs.virginia.edu/~whitehouse/matlab/JavaMatlab.html
In essence, call
MatlabControl.eval("yourfile.m");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.