1

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.

Suever
  • 64,497
  • 14
  • 82
  • 101
Sanakum
  • 179
  • 14

1 Answers1

2

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.

Suever
  • 64,497
  • 14
  • 82
  • 101
  • Thanks @Suever for your reply. `session.run('print_Name(name)')` may call this function. But how to take the returned string in a variable in `python` script? – Sanakum Nov 01 '18 at 17:15
  • Thanks Suever. That's what exactly I needed. – Sanakum Nov 01 '18 at 17:25