user17706769
user17706769

Reputation: 1

How to write a function that returns matrix with random values from a given range in Python?

I want to write a function that gives as input the dimension of the matrix (𝑛 × 𝑚) and a range of values (min, max) for possible entries in the matrix and have the return being a corresponding matrix with random values from the value range (return).

How to do that in Python?

Upvotes: 0

Views: 82

Answers (1)

radeklat
radeklat

Reputation: 542

In pure Python, you can use random.randint() to generate the random values and a list comprehension to generate the matrix. Example:

from random import randint

m=3
n=4
min_val=1
max_val=10

matrix=[[randint(min_val, max_val) for i in range(m)] for j in range(n)]

print(matrix)

Example output:

[[1, 2, 2], [1, 6, 7], [5, 9, 7], [2, 4, 10]]

Upvotes: 1

Related Questions