matlab调用python_从 MATLAB 调用 Python

调用 Python 函数使文本在段落内换行

MATLAB 具有 Python 标准库的大量等效功能,但并非全部。例如,textwrap 是一个模块,它可使用回车和其他便捷方式格式化文本块。MATLAB 同样提供了一个 textwrap 函数,但该函数只允许文本为适应 UI 控件而换行。

创建一个文本段落来进行测试。

T = 'MATLAB(R) is a high-level language and interactive environment for numerical computation, visualization, and programming. Using MATLAB, you can analyze data, develop algorithms, and create models and applications. The language, tools, and built-in math functions enable you to explore multiple approaches and reach a solution faster than with spreadsheets or traditional programming languages, such as C/C++ or Java(TM).';

将 Python 字符串转换为 MATLAB 字符串

通过在 textwrap.wrap 函数名称之前输入字符 py. 来调用该函数。请勿输入 import textwrap。

wrapped = py.textwrap.wrap(T);

whos wrapped

Name Size Bytes Class Attributes

wrapped 1x7 8 py.list

wrapped 是一个 Python 列表,它是一个 Python 字符串列表。MATLAB 将此类型显示为 py.list。

将 py.list 转换为 Python 字符串的元胞数组。

wrapped = cell(wrapped);

whos wrapped

Name Size Bytes Class Attributes

wrapped 1x7 840 cell

尽管 wrapped 是一个 MATLAB 元胞数组,但每个元胞元素均是一个 Python 字符串。

wrapped{1}

ans =

Python str with no properties.

MATLAB(R) is a high-level language and interactive environment for

使用 char 函数将 Python 字符串转换为 MATLAB 字符串。

wrapped = cellfun(@char, wrapped, 'UniformOutput', false);

wrapped{1}

ans =

'MATLAB(R) is a high-level language and interactive environment for'

现在每个元胞元素都是一个 MATLAB 字符串。

自定义段落

使用关键字参数自定义段落的输出。

前面的代码使用 wrap 便利函数,但模块使用 py.textwap.TextWrapper 功能提供更多选项。若要使用这些选项,请使用 https://docs.python.org/2/library/textwrap.html#textwrap.TextWrapper 所述的关键字参数调用 py.textwap.TextWrapper。

结合使用 MATLAB pyargs 函数与逗号分隔的名称/值对组列表创建关键字参数。width 将文本格式化为 30 个字符宽。initial_indent 和 subsequent_indent 关键字使每一行以 MATLAB 所用的注释字符 % 开头。

tw = py.textwrap.TextWrapper(pyargs(...

'initial_indent', '% ', ...

'subsequent_indent', '% ', ...

'width', int32(30)));

wrapped = wrap(tw,T);

转换为 MATLAB 参数并显示结果。

wrapped = cellfun(@char, cell(wrapped), 'UniformOutput', false);

fprintf('%s\n', wrapped{:})

% MATLAB(R) is a high-level

% language and interactive

% environment for numerical

% computation, visualization,

% and programming. Using

% MATLAB, you can analyze

% data, develop algorithms,

% and create models and

% applications. The language,

% tools, and built-in math

% functions enable you to

% explore multiple approaches

% and reach a solution faster

% than with spreadsheets or

% traditional programming

% languages, such as C/C++ or

% Java(TM).

了解更多信息

记得 Python 也可能提供 MATLAB 用户所需的库就足够了。如果您想了解 MATLAB 和 Python 之间的数据移动情况,包括元组和字典等 Python 数据类型,请参阅Python Libraries in MATLAB。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值