将使用MATLAB创建的矩阵转换为具有类似语法的Numpy数组

pet*_*hor 4 python numpy scipy

我正在玩我正在学习的课程的代码片段,最初是用MATLAB编写的.我使用Python并将这些矩阵转换为Python用于玩具示例.例如,对于以下MATLAB矩阵:

s = [2 3; 4 5];
Run Code Online (Sandbox Code Playgroud)

我用

s = array([[2,3],[4,5]])
Run Code Online (Sandbox Code Playgroud)

以这种方式重写所有玩具示例对我来说太耗费时间了,因为我只想看看它们是如何工作的.有没有办法直接将MATLAB矩阵作为字符串赋予Numpy数组或更好的替代方案?

例如,类似于:

s = myMagicalM2ArrayFunction('[2 3; 4 5]')
Run Code Online (Sandbox Code Playgroud)

roo*_*oot 6

numpy.matrix 可以将字符串作为参数.

Docstring:
matrix(data, dtype=None, copy=True)

[...]

Parameters
----------
data : array_like or string
   If `data` is a string, it is interpreted as a matrix with commas
   or spaces separating columns, and semicolons separating rows.
Run Code Online (Sandbox Code Playgroud)
In [1]: import numpy as np

In [2]: s = '[2 3; 4 5]'    

In [3]: def mag_func(s):
   ...:     return np.array(np.matrix(s.strip('[]')))

In [4]: mag_func(s)
Out[4]: 
array([[2, 3],
       [4, 5]])
Run Code Online (Sandbox Code Playgroud)