把简单的matlab/Octave脚本转换成python脚本的工具

http://stackoverflow.com/questions/9845292/a-tool-to-convert-matlab-code-to-python

这对于现有源代码的改写有帮助; 

但是,从编程的角度,应该还是原生态的好.


OMPC好用,但是Python 2.5支持最好;

SMOP一直在更新中(github),这个应该是目前最佳; Small  Matlab Octave Python首字母缩写;

不能指望借此就完全用Python替代Octave和Matlab,这也不是作者的初衷; 何况软件这么小,也很难完成那么复杂的工作.

这是一个跨平台的命令行下使用的工具,但仅在Linux上测试过; 

SMOP

SMOP stands for Small Matlab/Octave to Python compiler. It is used to convert Matlab programs to Python.

SMOP is not a polished product, nor a replacement to Octave and Matlab. Taking into account its size (less than 3000 lines), this is not surprizing. There are no toolboxes. Small everyday functions (max, length, etc.) are recognized and supported, but that's all.

SMOP is written in Python, using PLY -- Python Lex/Yacc for lexical analysis and parsing, and numpy for runtime environment. SMOP is platform-independent, but is tested only on Linux. It is a command-line utility.

Example

It is possible to run an example without installing smop. Just unzip it somewhere, and cd there. In your current directory you will find a bunch of .py files and a file named fastsolver.m. It is taken from the winning submission to Matlab programming competition in 2004 (Moving Furniturehttp://www.mathworks.cn/matlabcentral/contest/contests/12/submissions/29989).

Now type python main.py fastsolver.m -o fastsolver.py. If you don't specify the output file with -o option, it is written to a.py. Each time a function is translated, its name is written.

lei@fuji:~/smop/smop$ python main.py fastsolver.m
fastsolver.m
        solver
        cbest
        mainsolver
        imoves
        easysolver
        localfiddler
        findoverlaps
        dijkstra
        improve
        TLL79
        solverA
        solver1
        movefrompos
        onemove
        solver2
        SearchPath
        Faster10IntReps2
        matrixsolver
        outoftheway
        ismember1
        ismember2
        setdiff
        unique
        sub2ind
        randperm
        perms
        itTakesAThief
        movefurniture
        findshortestpath
        dealWall1
lei@fuji:~/smop/smop$

The entire submission contains 2093 lines, and it is automatically translated to Python by smop. These are the good news. The bad news are that generating the code is not enough to run the program, so there are no performance numbers yet.

  1. While the submission itself --- the solver program --- does not use graphics, the envelope code that is responsible to run the submission, collect and display the results, does. So about 100 lines of the envelope must be rewritten by hand.
  2. Many standard functions are not yet implemented --- rand, find, and others. They are on the issues list.
  3. Some matlab constructs, especially creating arrays by out of bound assignment, are used in the submission, but not yet supported by smop. Meanwhile, these lines should be rewritten in the Matlab code.
01 function moves=solver(A,B,w0)
02 [moves,optmove,optscore]=cbest(A,B,w0);
03 curscore=sum(w0(moves(:,1)));
04 lots=1;
05 if length(moves)-optmove<20||curscore/optscore<1.05
06     lots=2; return
07 else
08     lenw=length(w0);
09  [xx,nseq]=sort(rand(1,lenw));
10  A1=A;
11  B1=B;
12  w01=w0;
13  for i=1:lenw
14      A1(A==i)=nseq(i);
15      B1(B==i)=nseq(i);
16      w01(nseq(i))=w0(i);
17  end;
18  [moves2,optmove,optscore]=cbest(A1,B1,w01);

becomes

TBD

The table below tries to summarize various features.

Implemented features 
Lexical and syntactical analysisMostly complete, including some weird Matlab features
Name resolutionFor each occurrence of a variable, find a set of its possible definitions
Inlining of small functions 
Array subscripts translated from 1-based (Matlab and Fortran style) to 0-based (C and Python style)Also, end subscript implemented
from:step:to translated to from:to:step 
Upper bound is n+1 
Unimplemented features 
StructsTo be implemented as soon as cc possible.
Arrays silently become C=style (rows first).In some cases it may break the code. Not detected.
Function handles and lambda expressionsHandles break the heuristic that tells between function calls and array references.
Graphics,Never
Auto-expanding arraysUnlike other languages, matlab allows out-of-bounds assignment. As MathWorks tries to phase out this feature, there is a lot of legacy code depending on it.
Sparse matricesHave good chances of being implemented, especially taking into account that scipy have several implementations to choose from.
Full support for boolean indexing. Currently, some expressions don't workFor example, x(x>0.5) = 1 works, but y=x>0.5; x(y)=1 does not work.
Command syntaxToo complex to support
Type, rank and shape inference 
Strings



up vote 22 down vote accepted

There are several alternative tools for converting Matlab code to Python code (not tested yet):

Also, for those interested in an interface between the two languages and not conversion:

  • pymatlab: communicate from Python by sending data to the MATLAB workspace, operating on them with scripts and pulling back the resulting data
  • Python-Matlab wormholes: both directions of interaction supported
  • Python-Matlab bridge: use Matlab from within Python, offers matlab_magic for iPython, to execute normal matlab code from within ipython
  • PyMat: Control Matlab session from Python
  • pymat2: continuation of the appearingly abandoned PyMat.
  • mlabwrapmlabwrap-purepy: make Matlab look like Python library (based on PyMat)
  • oct2py: run GNU Octave commands from within Python
  • pymex: Embeds the Python Interpreter in Matlab, also on File Exchange
  • matpy: Access MATLAB in various ways: create variables, access .mat files, direct interface to MATLAB engine (requires MATLAB be installed).
  • MatPy: Python package for numerical linear algebra and plotting with a MatLab-like interface

Btw might be helpful to look here for other migration tips:

On a different note, though I'm not a fortran fan at all, for people who might find it useful there is:

share | edit | flag
  add comment

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 要将在MATLAB中编写的代码移植到Python中,有几种不同的方法可以使用,具体取决于你想要实现的功能和代码的复杂性。 以下是一些可能有用的技巧: 1. 使用Python的NumPy库代替MATLAB中的矩阵运算和线性代数操作。NumPy的语法和函数与MATLAB非常相似,因此可以轻松地将MATLAB代码换为NumPy。 2. 对于一些简单脚本,可以使用Python的内置函数和语法来实现相同的功能。例如,可以使用Python的for循环和if语句来替代MATLAB的循环和条件语句。 3. 在Python中使用Matplotlib库来生成类似于MATLAB绘图的图形。Matplotlib与MATLAB的绘图语法非常相似,因此可以轻松地将MATLAB代码换为Matplotlib。 4. 如果你的代码使用了MATLAB特定的工具箱或功能,例如信号处理或优化工具箱,你可能需要寻找Python的类似库或函数。可以在Python的科学计算库中查找相应的工具箱,例如SciPy库。 5. 有一些第三方工具可以将MATLAB代码换为Python代码。这些工具包括m2py和mat2py等,它们可以将MATLAB代码换为Python代码,并自动解决语法和语义差异。 需要注意的是,由于MATLABPython的语法和功能略有不同,因此在移植代码时可能会遇到一些挑战。但是,通过使用适当的工具和技术,可以轻松地将MATLAB代码换为Python代码,并实现相同的功能。 ### 回答2: 要将MATLAB中写的代码在Python中运行,可以采取以下几种方法: 1. 使用MATLAB Engine API for Python:MathWorks 提供了MATLAB Engine API for Python,可以直接在Python中调用MATLAB引擎,运行MATLAB代码。首先,需要安装MATLABMATLAB Engine API for Python。然后在Python中导入matlab引擎模块,并使用engine的eval方法来运行MATLAB代码。这种方法比较方便,但需要有MATLAB的许可证。 2. 使用开源工具OctaveOctave是一种与MATLAB相似的开源数值计算工具。可以将MATLAB代码换为Octave代码,并在Python中调用Oct2Py库来运行Octave代码。 3. 使用Python科学计算库:将MATLAB代码逐行翻译为Python代码,并使用Python的科学计算库,如NumPy、SciPy和Matplotlib等,来实现相同的功能。这种方法需要理解和翻译MATLAB代码,并可能需要对代码进行适当调整以适应Python语法和库的差异。 无论选择哪种方法,都需要仔细检查和调试代码,确保在Python中得到相同的结果。此外,还应注意库的差异和函数的功能的差异,以确保换后的代码能够在Python中正确运行。 ### 回答3: 将MATLAB中的代码在Python中运行,可以通过以下几种方法: 1. 使用MATLAB引擎库(MATLAB Engine API for Python):MathWorks提供了一个Python库,可以将MATLAB引擎与Python代码连接起来。该库允许在Python中调用MATLAB的函数和脚本。可以通过安装MATLAB并选择安装MATLAB引擎库来使用。 2. 使用MATLABPython代码工具:一些开源工具和库可以将MATLAB代码自动换为等效的Python代码。例如,m2py是一个将MATLAB代码换为Python代码的工具。可以将MATLAB代码输入到该工具中,并生成等效的Python代码,从而实现在Python中运行原来的MATLAB代码。 3. 手动将MATLAB代码换为Python代码:如果只有一小部分MATLAB代码需要换,或者找不到合适的工具,可以选择手动将MATLAB代码换为Python代码。这需要对MATLABPython语法的熟悉,并按照Python的语法规则进行相应的换。 无论选择哪种方法,都需要先熟悉基本的Python语法和函数,以及MATLAB代码的逻辑和功能。在换过程中,可能需要解决语法差异、库函数差异等问题。此外,如果涉及到MATLAB特定的功能或工具箱,可能需要在Python中找到相应的替代方法或库。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值