Convert a matrix created using MATLAB to a Numpy array with similar syntax

I play with code fragments of the course that I take, which is originally written in MATLAB. I use Python and convert these matrices to Python for toy examples. For example, for the following MATLAB matrix:

s = [2 3; 4 5]; 

I use

 s = array([[2,3],[4,5]]) 

Too much time for me to rewrite all the toy examples in this way, because I just want to see how they work. Is there a way to directly pass the MATLAB matrix as a string to a Numpy array, or is there a better alternative for this?

For example, something like:

 s = myMagicalM2ArrayFunction('[2 3; 4 5]') 
+4
source share
3 answers

numpy.matrix may take a string as an argument.

 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. 

 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]]) 
+6
source

How to simply save a set of example matrices in Matlab and load them directly in python:

http://docs.scipy.org/doc/scipy/reference/tutorial/io.html

EDIT:

or not sure how stable it is (just compiled a simple parser, which is probably better implemented in some other way), but something like:

 import numpy as np def myMagicalM2ArrayFunction(s): tok = [] for t in s.strip('[]').split(';'): tok.append('[' + ','.join(t.strip().split(' ')) + ']') b = eval('[' + ','.join(tok) + ']') return np.array(b) 

For 1D arrays, this will create a numpy array with the form (1, N), so you can use np.squeeze to get an array (N,) depending on what you are doing.

+2
source

If you want a NumPy array, not a NUMPY matrix

  def str_to_mat(x): x = x.strip('[]') return np.vstack(list(map(lambda r: np.array(r.split(','), dtype=np.float32), x.split(';')))) 
0
source

All Articles