Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,872 questions

51,796 answers

573 users

How to create an M x N matrix with random numbers in Python

1 Answer

0 votes
import random

ROWS = 4
COLS = 5

def print_matrix(matrix):
    # Print the matrix with aligned columns.
    for row in matrix:
        print("".join(f"{val:4d}" for val in row))

def generate_random_integer(min_val, max_val):
    # Generate a random integer between min_val and max_val inclusive.
    return random.randint(min_val, max_val)

def generate_random_matrix(rows, cols):
    # Generate a rows x cols matrix filled with random integers.
    return [[generate_random_integer(1, 100) for _ in range(cols)] for _ in range(rows)]

def main():
    # Seed random generator
    random.seed()

    matrix = generate_random_matrix(ROWS, COLS)
    print_matrix(matrix)

if __name__ == "__main__":
    main()



'''
run:

  59  92  31   3  86
  82   3  93  66  33
  77  39  54  37  16
  15   5  27  37  99

'''

 



answered Nov 22, 2025 by avibootz
edited Nov 22, 2025 by avibootz
...