Search code examples
matlabbatch-fileluacmdfunction-calls

Call a function by an external application without opening a new instance of Matlab


Is there a way to call Matlab functions from outside, in particular by the Windows cmd (but also the Linux terminal, LUA-scripts, etc...), WITHOUT opening a new instance of Matlab each time?

for example in cmd:

matlab -sd myCurrentDirectory -r "function(parameters)" -nodesktop -nosplash -nojvm

opens a new instance of Matlab relatively fast and executes my function. Opening and closing of this reduced matlab prompt takes about 2 seconds (without computations) - hence for 4000 executions more than 2 hours. I'd like to avoid this, as the called function is always located in the same workspace. Can it be done in the same instance always?

I already did some research and found the possibility of the MATLAB COM Automation Server, but it seems quite complicated to me and I don't see the essential steps to make it work for my case. Any advices for that?

I'm not familiar with c/c++/c# but I'm thinking about the use of python (but just in the worst case).


Solution

  • Based on the not-working, but well thought, idea of @Ilya Kobelevskiy here the final workaround:

     function pipeConnection(numIterations,inputFile)
    
     for i=1:numIterations
    
     while(exist('inputfile','file'))
    
         load inputfile;
         % read inputfile -> inputdata
         output = myFunction(inputdata);
    
         delete('inputfile');
     end
    
     % Write output to file
     % Call external application to process output data
     % generate new inputfile 
    
     end;
    

    Another convenient solution would be to compile an executable of the Matlab function:

    mcc -m myfunction
    

    run this .exe-file using cmd:

    cd myCurrentDirectory && myfunction.exe parameter1 parameter2
    

    Be aware that the parameters are now passed as strings and the original .m-file needs to be adjusted considering that.

    further remarks:

    • I guess Matlab still needs to be installed on the system, though it is not necessary to run it.
    • I don't know how far this method is limited respectively the complexity of the underlying function.
    • The speed-up compared to the initial apporach given in the question is relatively small