【问题标题】:How to run clojure from matlab如何从 matlab 运行 clojure
【发布时间】:2013-10-27 23:42:38
【问题描述】:

如何从 matlab 运行 clojure 脚本?

我尝试了以下操作: 用jdk 1.7运行matlab,然后调用java

MATLAB_JAVA=/usr/lib/jvm/java-7-oracle/jre matlab

在matlab中,设置classpath并使用clojure编译器

javaaddpath([pwd '/lib/clojure-1.5.1.jar'])
import clojure.lang.RT

这里出现错误:

Error using import
Import argument 'clojure.lang.RT' cannot be found or cannot be imported. 

当我编写运行 clojure 的 java 类时,一切都可以从控制台运行,但不能从 matlab 运行。 请指教。

【问题讨论】:

  • 据我记得,如果你想使用使用 Matlab 包含的不同 Java 版本(即 1.6)编译的类或 Java 包,Matlab 会遇到问题。
  • 我猜这就是他使用 MATLAB_JAVA 的原因。这应该使 matlab 使用指向的 jvm,而不是 MATLAB 中包含的 jvm。而且,由于这似乎是在 linux 系统上:MATLAB 只在 Windows 上带来自己的 jre,afaik。
  • 既然你说你想运行一个脚本,而不是调用 Clojure 函数或类似的东西,你不能用system 来做吗?
  • 这是我所做的解决方法。使用系统在单独的进程中运行 clojure,并将结果保存为临时文件中的 java 对象。然后从 matlab 读取这个文件。丑陋,但工作。
  • 您运行的是什么操作系统、操作系统版本和 Matlab 版本?

标签: matlab clojure classpath


【解决方案1】:

看起来这是 Clojure 不乐意从 Matlab 的“动态类路径”运行的问题。我使用捆绑的 JVM 或 Java 1.7.0u51 在 OS X 10.9 上使用 Matlab R2014a 时遇到了同样的错误。但是,如果我将 clojure-1.5.1.jar 添加到静态类路径中,将其放在 Matlab 启动目录中的自定义 javaclasspath.txt 中,那么 Clojure 类就会变得可见。

>> version -java
ans =
Java 1.7.0_51-b13 with Oracle Corporation Java HotSpot(TM) 64-Bit Server VM mixed mode
>> cloj = clojure.lang.RT
cloj =
clojure.lang.RT@77de6590

破解 Java 类路径

您使用this answer 中的“类路径黑客”方法从 Matlab 命令行向静态类路径添加条目,而不必使用自定义的 Matlab 设置。那里的答案涉及编写一个新的 Java 类,但您可以在纯 M 代码中执行等效操作。

function javaaddpathstatic(file)
%JAVAADDPATHSTATIC Add an entry to the static classpath at run time
%
% javaaddpathstatic(file)
%
% Adds the given file to the STATIC classpath. This is in contrast to the
% regular javaaddpath, which adds a file to the dynamic classpath.
%
% Files added to the path will not show up in the output of
% javaclasspath(), but they will still actually be on there, and classes
% from it will be picked up.
%
% Caveats:
% * This is a HACK and bound to be unsupported.
% * You need to call this before attempting to reference any class in it,
%   or Matlab may "remember" that the symbols could not be resolved.
% * There is no way to remove the new path entry once it is added.

parms = javaArray('java.lang.Class', 1);
parms(1) = java.lang.Class.forName('java.net.URL');
loaderClass = java.lang.Class.forName('java.net.URLClassLoader');
addUrlMeth = loaderClass.getDeclaredMethod('addURL', parms);
addUrlMeth.setAccessible(1);

sysClassLoader = java.lang.ClassLoader.getSystemClassLoader();

argArray = javaArray('java.lang.Object', 1);
jFile = java.io.File(file);
argArray(1) = jFile.toURI().toURL();
addUrlMeth.invoke(sysClassLoader, argArray);

所以,使用 javaaddpathstatic() 而不是 javaaddpath(),您的代码可能会工作。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
相关资源
最近更新 更多