MATLAB 中如何使用 import

📅 2026/7/28 16:03:02 👁️ 阅读次数 📝 编程学习
MATLAB 中如何使用 import

不要输入 import pythonmodule

MATLAB 会自动加载 Python 当输入

py.command

因为不用输入 import pythonmodule 。

MATLAB 中的 import 语句作用与 Python 中不同。Python使用 import 语句加载代码并使之能够访问。MATLAB使用 import 函数是为了不用包名就可以直接使用类或函数。

使用 import 缩短类和函数名

Python 的 from...import 语句使我们在不使用完全限定名称的情况下引用模块。

在 Python 中 import 语句为:

from x import y

在 MATLAB 中则为

import x.y

其中 y 为类名或函数名。

实例:

Python 中的 textwrap 模块可以格式化文本块:

S = py.textwrap.wrap('This is a string');

其中 wrap 并不是 MATLAB 函数,就可以使用 import 函数来缩短调用语句。

import py.textwrap.wrap S = wrap('This is a string');

注意

不要使用:

import py.*

上式会让 MATLAB 使用所有的 Python函数,从而覆盖掉重名的 MATLAB 函数。

此命令可以通过下面的命令去除:

clear import

参考资料:

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