Create numpy array from matrix declared inside .m matlab file

后端 未结 2 756
时光说笑
时光说笑 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条回答
  •  萌比男神i
    2021-01-22 13:15

    You could feed an iterator to np.genfromtxt:

    import numpy as np
    import re
    
    with open(filename, 'r') as f:
        lines = (re.sub(r'[^-+.0-9 ]+', '', line) for line in f)
        arr = np.genfromtxt(lines)
    
    print(arr)
    

    yields

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

    Thanks to Bitwise for clueing me in to this answer.

提交回复
热议问题