目录
在 Python 中使用 MATLAB 数组
示例说明如何在 Python® 中创建 MATLAB® 数组并将其作为输入参数传递给 MATLAB sqrt 函数。
matlab 包提供了构造函数以支持在 Python 中创建 MATLAB 数组。用于 Python 的 MATLAB 引擎 API 可以将此类数组作为输入参数传递给 MATLAB 函数,并且可以将此类数组作为输出参数返回给 Python。可以从 Python 序列类型创建任何 MATLAB 数值或逻辑值类型的数组。
从 Python list创建一个 MATLAB 数组。对该数组调用 sqrt 函数。
import matlab.engine eng = matlab.engine.start_matlab() a = matlab.double([1,4,9,16,25]) b = eng.sqrt(a) print(b) [[1.0,2.0,3.0,4.0,5.0]]
引擎返回 b,它是 1×5 的 matlab.double 数组。创建一个多维数组。magic 函数将一个二维 matlab.double 数组返回给 Python。使用 for 循环分行打印数组中的每行。(当看到 ... 提示时再次按 Enter 以关闭循环并打印。)
a = eng.magic(6) for x in a: print(x) ... [35.0,1.0,6.0,26.0,19.0,24.0] [3.0,32.0,7.0,21.0,23.0,25.0] [31.0,9.0,2.0,22.0,27.0,20.0] [8.0,28.0,33.0,17.0,10.0,15.0] [30.0,5.0,34.0,12.0,14.0,16.0] [4.0,36.0,29.0,13.0,18.0,11.0]
调用 tril 函数来获取 a 的下三角部分。在一个单独的行上打印数组中的每行。
b = eng.tril(a) for x in b: print(x) ... [35.0,0.0,0.0,0.0,0.0,0.0] [3.0,32.0,0.0,0.0,0.0,0.0] [31.0,9.0,2.0,0.0,0.0,0.0] [8.0,28.0,33.0,17.0,0.0,0.0] [30.0,5.0,34.0,12.0,14.0,0.0] [4.0,36.0,29.0,13.0,18.0,11.0]