简体   繁体   中英

numpy: Print matrix with random elements, columns and rows

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM