ConnectJavato RunningMATLABSession
Find and Connect toMATLAB
You can connect the Java®engine to shared MATLAB®sessions that are running on the local machine. To connect to a shared MATLAB session:
Start MATLAB as a shared engine session, or make a running MATLAB process shared using
matlab.engine.shareEngine
.Find the names of the MATLAB shared sessions using the
MatlabEngine.findMatlab
orMatlabEngine.findMatlabAsync
static method.Pass the string containing the name of the shared MATLAB session to the
MatlabEngine.connectMatlab
orMatlabEngine.connectMatlabAsync
static method. These methods connect the Java engine to the shared session.
If you do not specify the name of a shared MATLAB session when callingMatlabEngine.connectMatlab
orMatlabEngine.connectMatlabAsync
,引擎使用第一MATL共享AB session created. If there are no shared MATLAB sessions available, the engine creates a shared MATLAB session and connects to this session.
For a description of these methods, seecom.mathworks.engine.MatlabEngine
连接到MATLABSynchronously
Convert the MATLAB session to a shared session by callingmatlab.engine.shareEngine
from MATLAB.
matlab.engine.shareEngine
Find the session and connect synchronously from Java.
进口com.mathworks.engine。*;public class javaFindConnect { public static void main(String[] args) throws Exception { String[] engines = MatlabEngine.findMatlab(); MatlabEngine eng = MatlabEngine.connectMatlab(engines[0]); // Execute command on shared MATLAB session eng.eval("plot(1:10); print('myPlot','-djpeg')"); eng.close(); } }
连接到MATLABAsynchronously
Convert the MATLAB session to a shared session by callingmatlab.engine.shareEngine
from MATLAB.
matlab.engine.shareEngine
Find the session and connect asynchronously from Java.
进口com.mathworks.engine。*;进口java.util.concurrent.Future; public class javaFindConnectAsync { public static void main(String[] args) throws Exception { FutureeFuture = MatlabEngine.findMatlabAsync(); String[] engines = eFuture.get(); Future engFuture = MatlabEngine.connectMatlabAsync(engines[0]); // Work on other thread MatlabEngine eng = engFuture.get(); // Execute command on shared MATLAB session Future vFuture = eng.evalAsync("plot(1:10); print('myPlot','-djpeg')"); eng.close(); } }
Specify Name of Shared Session
You can specify the name of the shared MATLAB session when you execute thematlab.engine.shareEngine
MATLAB function. Doing so eliminates the need to useMatlabEngine.findMatlab
orMatlabEngine.findMatlabAsync
to find the name.
For example, start MATLAB and name the shared sessionmyMatlabEngine
.
matlab -r "matlab.engine.shareEngine('myMatlabEngine')"
连接到the named MATLAB session from Java.
进口com.mathworks.engine。*;public class javaNameConnect { public static void main(String[] args) throws Exception { String[] myEngine = {"myMatlabEngine"}; MatlabEngine eng = MatlabEngine.connectMatlab(myEngine[0]); // Execute command on shared MATLAB session eng.eval("plot(1:10); print('myPlot','-djpeg')"); eng.close(); } }