0

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?

1

2 Answers 2

1

After that, just use

np.array(matrix, dtype=float)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer, Girardi! But isn't this going to be a matrix of int numbers?
You can specify a dtype in np.array(..., dtype=float)
0

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.]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.