如何使用matlabcontrol.jar从Java调用用户定义的Matlab [英] How to call a user defined Matlab from Java using matlabcontrol.jar
问题描述
我正在尝试调用用户定义的Matlab函数(M文件),该函数从我在Eclipse中开发的Java应用程序中获取3个参数(Java字符串)。目前,我可以使用函数/命令(如<$)调用 proxy.eval
和 proxy.feval
方法c $ c> disp 或 sqr
。但是当我尝试调用一个用户定义的函数时,它在matlab控制台上说没有像这样定义的函数,并且在Java控制台上发生 MatlabInvocationException
。
I am trying to call a user defined Matlab Function(M file) which takes 3 arguments(Java Strings) from my Java application which is developed in Eclipse. At the moment I am able to call proxy.eval
and proxy.feval
methods with the functions/commands like disp
or sqr
. But when i try to invoke a user-defined function it says on the matlab console that there is no such function defined like that and on the Java console MatlabInvocationException
occurs.
然后我尝试使用一个简单的用户定义函数,该函数不带参数,只有单行 disp('Hello')
但结果仍然相同。所以我认为而不是类型转换问题,如何调用用户定义的函数是错误的。
Then I tried with a simple user-defined function which takes no arguments and just has single line disp('Hello')
but still the result is same. So I think rather than a type conversion problem there is something wrong with how user-defined functions are getting invoked.
请问有人能帮助我吗?我很快就会完成这个项目的截止日期。如果有人能提出解决方案,我会非常感激。 (Joshuwa Kaplan先生,有没有关于在你的帖子中解决这类问题的指南?我试过但却一无所获)
Please can anyone help me soon? I am meeting the deadline very soon for this project. I would be so thankful if someone can come up with a solution. (Mr Joshuwa Kaplan, is there any guide on solving an issue like this in your posts? I tried but found nothing)
提前致谢
推荐答案
您必须在 MATLAB搜索路径上有任何用户定义的m文件,就像在MATLAB中正常工作一样。
You must have any user-defined m-files on the MATLAB search path, just as if you were working normally inside MATLAB.
我使用以下示例进行了测试:
I tested with the following example:
function myfunc()
disp('hello from MYFUNC')
end
HelloWorld.java
HelloWorld.java
import matlabcontrol.*;
public class HelloWorld
{
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.eval("addpath('C:\\some\\path')");
proxy.feval("myfunc");
proxy.eval("rmpath('C:\\some\\path')");
// close connection
proxy.disconnect();
}
}
我们编译并运行Java程序:
We compile and run the Java program:
javac -cp matlabcontrol-4.0.0.jar HelloWorld.java
java -cp ".;matlabcontrol-4.0.0.jar" HelloWorld
将打开一个MATLAB会话,并显示输出:
a MATLAB session will open up, and display the output:
hello world
hello from MYFUNC
您也可以将文件夹添加到路径一次,然后使用SAVEPATH将其保留。这样你就不必每次都这样做。
You could also add your folder to the path once, then persist it using SAVEPATH. That way you won't have to do it each time.
这篇关于如何使用matlabcontrol.jar从Java调用用户定义的Matlab的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!