MATLAB 中调用自定义 Python 模块

此处用实例来说明如何调用自定义的 Python 模块。

改变当前文件夹为可写文件夹

在 MATLAB 编辑器中打开一个新文件

复制下述命令到新文件,并重命名为 mymod.py

# mymod.py
"""Python module demonstrates passing MATLAB types to Python functions"""
def search(words):
    """Return list of words containing 'son'"""
    newlist = [w for w in words if 'son' in w]
    return newlist

def theend(words):
    """Append 'The End' to list of words"""
    words.append('The End')
    return words

从 MATLAB 命令行添加当前文件夹到 Python 搜索路径。

if count(py.sys.path,'') == 0
    insert(py.sys.path,int32(0),'');
end

实例

在 MATLAB 中,创建一个 list,作为输入参数。

N = py.list({'Jones','Johnson','James'})

结果:

N = 

  Python list (不带属性)。

    ['Jones', 'Johnson', 'James']

调用 search 函数。在模块名称和函数名前输入 py.

names = py.mymod.search(N)

结果:

names = 

  Python list (不带属性)。

    ['Johnson']

函数返回一个 py.list 对象,原始输入 N 不变。

参考资料:

1.MATLAB 官方文档:https://ww2.mathworks.cn/help/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值