Create numpy array from matrix declared inside .m matlab file

后端 未结 2 749
时光说笑
时光说笑 2021-01-22 12:22

A coworker left some data files I want to analyze with Numpy.

Each file is a matlab file, say data.m, and have the following formatting (but with a lot more

2条回答
  •  灰色年华
    2021-01-22 13:08

    Here are a couple options, although neither is built in.

    The solution you probably do not find acceptable

    This solution probably falls into your "quick and dirty" category, but it helps lead in to the next solution.

    Remove the values = [, the last line (];), and globally replace all ; with nothing to get:

    -24.92 -23.66 -22.55 
    -24.77 -23.56 -22.45 
    -24.54 -23.64 -22.56 
    

    Then you can use numpy's loadtxt as follows.

    >>> import numpy as np
    >>> A = np.loadtxt('data.m')
    
    >>> A
    array([[-24.92, -23.66, -22.55],
           [-24.77, -23.56, -22.45],
           [-24.54, -23.64, -22.56]])
    

    A solution you might find acceptable

    In this solution, we create a method to coerce the input data into a form that numpy loadtxt likes (the same form as above, actually).

    import StringIO
    import numpy as np
    
    def convert_m(fname):
        with open(fname, 'r') as fin:
            arrstr = fin.read()
        arrstr = arrstr.split('[', 1)[-1] # remove the content up to the first '['
        arrstr = arrstr.rsplit(']', 1)[0] # remove the content after ']'
        arrstr = arrstr.replace(';', '\n') # replace ';' with newline
        return StringIO.StringIO(arrstr)
    

    Now that we have that, do the following.

    >>> np.loadtxt(convert_m('data.m'))
    array([[-24.92, -23.66, -22.55],
           [-24.77, -23.56, -22.45],
           [-24.54, -23.64, -22.56]])
    

提交回复
热议问题