4

I'm playing with the code snippets of the course I'm taking which is originally written in MATLAB. I use Python and convert these matrices to Python for the toy examples. For example, for the following MATLAB matrix:

s = [2 3; 4 5];

I use

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

It is too time consuming for me to re-write all the toy examples this way because I just want to see how they work. Is there a way to directly give the MATLAB matrix as string to a Numpy array or a better alternative for this?

For example, something like:

s = myMagicalM2ArrayFunction('[2 3; 4 5]')
2
  • np.matrix actually supports some strings more similar to matlab (maybe it does yours), but I would try to avoid it personally... also in numpy it is usually better to avoid matrices, so do convert it to an array afterwards. Commented Apr 3, 2013 at 13:34
  • Thanks @seberg. I would also prefer array approach instead of Matrix. Commented Apr 3, 2013 at 13:37

4 Answers 4

6

numpy.matrix can take 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]])
Sign up to request clarification or add additional context in comments.

3 Comments

Then, np.array(np.matrix(s.strip('[]'))) will do the same magic. It looks more compact.
+1 since I hardly ever use np.matrix, I didn't know that it takes a string as an input. Good trick to know. Thanks
@petrichor -- added a full example.
2

How about just saving a set of example matrices in Matlab and load them directly into python:

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

EDIT:

or not sure how robust this is (just threw together 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 shape (1,N), so you might want to use np.squeeze to get a (N,) shaped array depending on what you are doing.

2 Comments

This requires MATLAB I think and it is more time consuming for me.
@petrichor Ok, see the edit for a simple string parser that works for your example.
0

If you want a numpy array rather than 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(';'))))

Comments

0

One can do the following to translate any format of MATLAB matrix to a numpy array:

def myMagicalM2ArrayFunction(s):
    rule = '[\d]*[.][\d]+|[\d]+'
    s = s[1:-1]
    s = s.split(';')
    nlists = []
    for item in s:
        nlist = []
        if re.search(rule, item) is not None:
            for catch in re.finditer(rule, item):
                nlist.append(int(catch[0])) if catch[0].isdigit() else nlist.append(float(catch[0]))
        nlists.append(nlist)
    return np.array(nlists)

Example 1:

import re
import numpy as np
s = myMagicalM2ArrayFunction('[2 3; 4 5]')

Output 1:

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

Example 2:

s = myMagicalM2ArrayFunction('[ 0.2 3;4.3 5 ]')

Output 2:

array([[0.2, 3. ],
       [4.3, 5. ]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.