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.

1 Answer 1

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.

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

2 Comments

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?
Thanks Suever. That's what exactly I needed.

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.