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

查看:208
本文介绍了从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 Files\MATLAB\R2008a\toolbox\matlab\general\perl.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中

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

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

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