How to to read a matrix from a given file?

前端 未结 7 629
傲寒
傲寒 2020-12-09 17:41

I have a text file which contains matrix of N * M dimensions.

For example the input.txt file contains the following:



        
相关标签:
7条回答
  • 2020-12-09 18:27

    You can simply use numpy.loadtxt. Easy to use, and you can also specify your delimiter, datatypes etc.

    specifically, all you need to do is this:

    import numpy as np
    input = np.loadtxt("input.txt", dtype='i', delimiter=',')
    print(input)
    

    And the output would be:

    [[0 0 0 0 0 0 0 0 0 0]
     [0 0 0 0 0 0 0 0 0 0]
     [0 0 0 0 0 0 0 0 0 0]
     [0 0 0 0 0 0 0 0 0 0]
     [0 0 0 0 0 0 0 0 0 0]
     [0 0 0 0 0 0 0 0 0 0]
     [0 0 2 1 0 2 0 0 0 0]
     [0 0 2 1 1 2 2 0 0 1]
     [0 0 1 2 2 1 1 0 0 2]
     [1 0 1 1 1 2 1 0 2 1]]
    
    0 讨论(0)
提交回复
热议问题