Search code examples
pythonmatlabmatlab-engine

How to call a matlab function file from python using the matlab engine API?


I have a matlab function file called 'calculate_K_matrix.m ' which contains the following code:

function K = calculate_K_matrix(A, B, n)

K = place(A, B, eigs(A)*n)

end

I can call this from matlab like so:

addpath('/home/ash/Dropbox/SimulationNotebooks/Control')

A = [0 1 ;-100 -5]
B = [0 ; 7]


n = 1.1 % how aggressive feedback is

K = calculate_K_matrix(A, B, n)

but when I try to call this from python using the matlab engine API like so:

import matlab                                                                                                       
import matlab.engine                                                                                                

eng = matlab.engine.start_matlab()                                                                                  

A = matlab.double([[0, 1],[-100, -5]])                                                                              
B = matlab.double([[0],[7]])                                                                                        
n = 1.1                  double(param initializer=None, param size=None, param is_complex=False)                    
n_matlab = matlab.double([n])                                                                                       

eng.addpath(r'/home/ash/Dropbox/SimulationNotebooks/Control')                                                       
K = eng.calculate_K_matrix(A, B, n_matlab) 

Then I get the following error:

In [17]: run test.py
Attempt to execute SCRIPT calculate_K_matrix as a function:
/home/ash/Dropbox/SimulationNotebooks/Control/calculate_K_matrix.m

---------------------------------------------------------------------------
MatlabExecutionError                      Traceback (most recent call last)
/home/ash/Dropbox/SimulationNotebooks/Control/test.py in <module>()
     10 
     11 eng.addpath(r'/home/ash/Dropbox/SimulationNotebooks/Control')
---> 12 K = eng.calculate_K_matrix(A, B, n_matlab)

/home/ash/anaconda2/envs/python3/lib/python3.5/site-packages/matlab/engine/matlabengine.py in __call__(self, *args, **kwargs)
     76         else:
     77             return FutureResult(self._engine(), future, nargs, _stdout,
---> 78                                 _stderr, feval=True).result()
     79 
     80     def __validate_engine(self):

/home/ash/anaconda2/envs/python3/lib/python3.5/site-packages/matlab/engine/futureresult.py in result(self, timeout)
     66                 raise TypeError(pythonengine.getMessage('TimeoutCannotBeNegative'))
     67 
---> 68         return self.__future.result(timeout)
     69 
     70     def cancel(self):

/home/ash/anaconda2/envs/python3/lib/python3.5/site-packages/matlab/engine/fevalfuture.py in result(self, timeout)
     80                 raise TimeoutError(pythonengine.getMessage('MatlabFunctionTimeout'))
     81 
---> 82             self._result = pythonengine.getFEvalResult(self._future,self._nargout, None, out=self._out, err=self._err)
     83             self._retrieved = True
     84             return self._result

MatlabExecutionError: Attempt to execute SCRIPT calculate_K_matrix as a function:
/home/ash/Dropbox/SimulationNotebooks/Control/calculate_K_matrix.m

How can I solve this issue?


Solution

  • Use getattr, like:

       import matlab.engine
        engine = matlab.engine.start_matlab()
        engine.cd('<your path>')
        getattr(engine, 'calculate_K_matrix')(A, B, n, nargout=0)
    

    Thats how I do it:

    import matlab.engine, sys, cmd, logging
    
    
    class MatlabShell(cmd.Cmd):
        prompt = '>>> '
        file = None
    
        def __init__(self, engine = None, completekey='tab', stdin=None, stdout=None):
            if stdin is not None:
                self.stdin = stdin
            else:
                self.stdin = sys.stdin
            if stdout is not None:
                self.stdout = stdout
            else:
                self.stdout = sys.stdout
                self.cmdqueue = []
                self.completekey = completekey
    
            if engine == None:
                try:
                    print('Matlab Shell v.1.0')
                    print('Starting matlab...')
                    self.engine = matlab.engine.start_matlab()
                    print('\n')
                except:
                    logging.exception('>>> STARTUP FAILED')
                    input()
            else:
                self.engine = engine
    
            self.cmdloop()
    
        def do_run(self, line):
            try:
                getattr(self.engine, line)(nargout=0)
            except matlab.engine.MatlabExecutionError:
                pass
    
        def default(self, line):
            try:
                getattr(self.engine, 'eval')(line, nargout=0)
            except matlab.engine.MatlabExecutionError:
                pass
    
    
    if __name__ == "__main__":
        MatlabShell()
    

    pictures: Result function