2

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?

7
  • Is calculate_K_matrix a function or a script? because it looks like its a script Commented Mar 1, 2018 at 15:16
  • it's a script that contains a single function of the same name. Commented Mar 1, 2018 at 15:17
  • I was told if I wanted to use the function outside of matlab the function needed to have the same name as the script? Commented Mar 1, 2018 at 15:17
  • 1
    You are correct, that makes it a function file, not a script. Read more info here: uk.mathworks.com/help/matlab/matlab_prog/… Commented Mar 1, 2018 at 15:19
  • Ok, thanks, I've updated the question to reflect this. Commented Mar 1, 2018 at 15:27

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.