numpy: Print matrix with random elements, columns and rows

旧街凉风 提交于 2021-02-11 14:30:19

问题


I want a matrix to be printed with random columns(0, 9) and random rows(0, 9) with random elements(0, 9)
Where (0, 9) is any random number between 0 and 9.


回答1:


If what you're looking for is a 10x10 matrix filled with random numbers between 0 and 9, here's what you want:

# this randomizes the size of the matrix.
rows, cols = np.random.randint(9, size=(2))
# this prints a matrix filled with random numbers, with the given size.
print(np.random.randint(9, size=(rows, cols)))

Output:

[[1 7 1 4 4 4 4 3]
 [1 4 7 3 0 5 3 5]
 [6 3 3 7 5 7 6 1]
 [3 8 5 7 2 0 1 6]
 [5 0 8 5 0 1 5 1]
 [1 3 3 7 3 7 5 6]
 [3 7 4 1 8 3 7 8]
 [8 8 8 5 8 4 7 1]]



回答2:


First, randomize your number of columns and rows:

import numpy as np

rows, cols = np.random.randint(10, size = 2)

If you want a matrix of integers just try:

m = np.random.randint(10, size = (rows,cols))

This will output a rows x cols matrix with random numbers in the close interval [0,9].

If you want a matrix of float numbers just try:

m = np.random.rand(rows,cols) * 9

This will output a rows x cols matrix with random numbers in the close interval [0,9].



来源:https://stackoverflow.com/questions/51353704/numpy-print-matrix-with-random-elements-columns-and-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!