Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a matrix created with MATLAB to Numpy array with a similar syntax

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]')
like image 542
petrichor Avatar asked Feb 17 '23 22:02

petrichor


2 Answers

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]])
like image 100
root Avatar answered May 03 '23 17:05

root


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.

like image 25
JoshAdel Avatar answered May 03 '23 18:05

JoshAdel