Putting an eclipse project in a matlab for loop

3 views (last 30 days)
I am trying to connect Matlab, COMSOL (a finite element software), and a program built in Eclipse into 1 program under a 'for' loop. Connecting COMSOL and Matlab is done because of Livelink which is simple. Now, the trouble Im having is connecting Matlab to Eclipse.
Basically, I want Matlab to run the comsol program, write an XML file, have Matlab then run the java program and then restart the loop.
Any suggestions or help where to look would be greatly appreciated!

Answers (1)

Aniket
Aniket on 8 Apr 2025
I understood that you’re creating a workflow where MATLAB runs a simulation in COMSOL via LiveLink, writes an XML, then runs a Java program (from Eclipse) to process that XML, and then loops back. MATLAB can call Java code directly, assuming you compile your Java code (from Eclipse) into a .jar. Once compiled, MATLAB can:
  1. Load the JAR
  2. Instantiate Java classes
  3. Call methods
  4. Loop back into the COMSOL simulation
This makes your for loop control fully centralized inside MATLAB.
Follow the below mentioned steps to run Java code from MATLAB:
  1. Compile Java Program to JAR
In Eclipse:
  • Right-click your project > Export > Java > JAR file
  • Export the compiled class into MyProcessor.jar
Make sure your main class looks like:
public class MyProcessor {
public static void process(String xmlFilePath) {
// Your logic here
System.out.println("Processing " + xmlFilePath);
// ...
}
}
2. Load JAR into MATLAB
Place the .jar in MATLAB path or current working directory.
javaaddpath('MyProcessor.jar');
Call the method like this:
javaMethod('process', 'MyProcessor', 'C:/path/to/myInput.xml');
or if it's a static method:
MyProcessor.process('C:/path/to/myInput.xml');
The final full control loop looks like this:
javaaddpath('MyProcessor.jar'); % Add once before loop
for i = 1:N
% Run COMSOL simulation
model = mphopen('yourModel.mph');
model.study('std1').run;
% Export results to XML
exportXML(model, sprintf('run_%d.xml', i));
% Process XML with Java
MyProcessor.process(sprintf('C:/path/run_%d.xml', i));
end
Note: If your Java code relies on additional libraries, or you don’t want to tightly couple it with MATLAB’s JVM, use the following approach:
% Build system command
cmd = 'java -cp "C:\path\to\MyProcessor.jar" MyProcessor C:\path\to\input.xml';
% Call from MATLAB
[status, cmdout] = system(cmd);
disp(cmdout);
I hope this helps achieve the desired functionality.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!