Search code examples
pythonmatlabpymatlab

Call Matlab function from Python script using pymatlab


Can anyone give me an idea about how to call Matlab function from python script using pymatlab?

Matlab, pymatlab and python are already properly installed. I tried to run some Matlab commands from here on python script and everything works fine. But I have no idea regarding calling Matlab function from python.

For example, I have a Matlab function which will receive a string as argument and will display it and return it, like below.

function [ name ] = print_Name(first_Name)
name=first_Name;
end

Thanks in advance for your kind suggestion.


Solution

  • You need to first initialize a MATLAB session

    import pymatlab
    session = pymatlab.session_factory()
    

    Then you can use the run method to call any MATLAB function that you wish

    session.run("print_Name('name')")
    

    Or you could assign a value in the workspace and use that

    name = 'My Name'
    session.putValue('name', name)
    session.run('print_Name(name)')
    

    If you want to get a value back, you can always assign the output of print_Name to a variable and call session.getValue to get that back into Python

    session.run('output = print_Name(name)')
    result = session.getValue('output')
    

    That being said, I would highly recommend using The Mathwork's own library for interacting with MATLAB from Python.