此处用实例来说明如何调用自定义的 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/