从 MATLAB 调用 Python 函数 [英] Call Python function from MATLAB

查看:36
本文介绍了从 MATLAB 调用 Python 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从 MATLAB 调用 Python 函数.我该怎么做?

I need to call a Python function from MATLAB. how can I do this?

推荐答案

我的系统也有类似的需求,这是我的解决方案:

I had a similar requirement on my system and this was my solution:

在 MATLAB 中有一个名为 perl.m 的函数,它允许您从 MATLAB 调用 perl 脚本.根据您使用的版本,它将位于诸如

In MATLAB there is a function called perl.m, which allows you to call perl scripts from MATLAB. Depending on which version you are using it will be located somewhere like

C:Program FilesMATLABR2008a	oolboxmatlabgeneralperl.m

创建一个名为 python.m 的副本,快速搜索并用 python 替换 perl,仔细检查它设置的指向您安装的 python 的命令路径.您现在应该可以从 MATLAB 运行 python 脚本了.

Create a copy called python.m, a quick search and replace of perl with python, double check the command path it sets up to point to your installation of python. You should now be able to run python scripts from MATLAB.

示例

python 中一个简单的平方函数保存为sqd.py",自然如果我这样做得当,我会在测试输入参数、有效数字等方面进行一些检查.

A simple squared function in python saved as "sqd.py", naturally if I was doing this properly I'd have a few checks in testing input arguments, valid numbers etc.

import sys

def squared(x):
    y = x * x
    return y

if __name__ == '__main__':
    x = float(sys.argv[1])
    sys.stdout.write(str(squared(x)))

然后在 MATLAB 中

Then in MATLAB

>> r=python('sqd.py','3.5')
r =
12.25
>> r=python('sqd.py','5')
r =
25.0
>>

这篇关于从 MATLAB 调用 Python 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆