Home > Blockchain >  How can I create a numpy matrix of floats from input?
How can I create a numpy matrix of floats from input?

Time:10-24

I'm trying to create a matrix of floats from the user's input.

I've tried this code:

import numpy as np 

m = int(input('Number of lines m: '))

matrix = []
for i in range(m):
   # taking row input from the user
   row = list(map(int, input(f'Line {i} ').split()))
   # appending the 'row' to the 'matrix'
   matrix.append(row)
    
print(matrix)

How can I turn that into a numpy matrix of floats?

CodePudding user response:

After that, just use

np.array(matrix)

CodePudding user response:

A nice basic input:

In [80]: alist = []
    ...: for _ in range(3):
    ...:     astr=input()
    ...:     alist.append(astr.split())
    ...: arr = np.array(alist, float)
1 2 3
4 5 6
7 8 9
In [81]: alist
Out[81]: [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
In [82]: arr
Out[82]: 
array([[1., 2., 3.],
       [4., 5., 6.],
       [7., 8., 9.]])

We could enhance it with the ability to set the number of rows, and check that the number of substrings are consistent. But this shows the basic structue.

But for making an array for testing, I prefer to use something like:

In [83]: np.arange(1,10).astype(float).reshape(3,3)
Out[83]: 
array([[1., 2., 3.],
       [4., 5., 6.],
       [7., 8., 9.]])
  • Related