How to run .m file in python?

Illustration
Xinfeng Li - 2025-01-15T13:05:56+00:00
Question: How to run .m file in python?

I have a .m code what I want to run in python. Is it any easy way? 1. this code is not a function. 2. don't want to show the matlab window.  

Expert Answer

Profile picture of Kshitij Singh Kshitij Singh answered . 2025-11-20

This is not a big deal. The python code looks like:
import matlab.engine
eng = matlab.engine.start_matlab()
eng.simple_script(nargout=0)
eng.quit()

The Matlab script would be perhaps this one line saved as simple_script.m:

a = 'it works easily...'
Make sure that the script is saved in a folder matlab knows as a search folder.
Then run your python script and get the answer:
a =
    'it works easily...'
It is not necessary that you have a function in your .m-file, but possible. See more information here.
The Matlab screen is not visible by default, so you should be happy if you follow this and the linked information...


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!