How to run .m file in python

398 次查看(过去 30 天)
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.
Best Regards
Xinfeng

采纳的回答

Stephan
Stephan 2018-8-21
编辑:Stephan 2018-8-21
Hi,
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...
Best regards
Stephan
  5 个评论
Ankit Jaiswal
Ankit Jaiswal 2020-2-8
It doesnt work in Anaconda-spyder. Try in Pycharm, it will work.
swagat shovan
swagat shovan 2020-3-6
it works in anaconda spyder but u gave to install anaconda 3.4 or below for matlab 2016b or according to the python package present in matlab.
you can check the python package available in matlab from matlabroot\extern\engines\python path
for safe side install anaconda 2.7 or 3.0 and
goto> anaconda prompt and type
cd "matlabroot\extern\engines\python"
python setup.py install

请先登录,再进行评论。

更多回答(1 个)

David Gonzalez
David Gonzalez 2019-3-28
How can I do this if the script is in another folder?
Thanks!
  3 个评论
Yihui Quek
Yihui Quek 2019-7-22
I think the OP means, 'what should I add to my Python script if I want it to run a matlab script in a different folder?' Your command is a Matlab command, which doesn't help if the Matlab script can't even be found by Python.
Huang Chi-En
Huang Chi-En 2020-3-10
编辑:Huang Chi-En 2020-3-10
The classical python function :
# python..
import sys
positionOfPath = 1
sys.path.insert( positionOfPath, 'your matlab path' )
# end of python
may help python find the path to access the matlab script ~~

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Call Python from MATLAB 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by