J.Doe
J.Doe

Reputation: 1552

Creating a random matrix in python

I am trying to create a random square matrix of nxn random numbers with numpy. Of course I am able to generate enough random numbers but I am having trouble using numpy to create a matrix of variable length. This is as far as I have gotten thus far:

def testMatrix(size):
    a = []
    for i in range(0, size*size):
        a.append(randint(0, 5))

How can I put this list into an array of size x size?

Upvotes: 3

Views: 7918

Answers (2)

ChootsMagoots
ChootsMagoots

Reputation: 680

Try

np.random.randint(0, 5, size=(s, s))

Upvotes: 4

kooshywoosh
kooshywoosh

Reputation: 571

Your test matrix is currently one dimensional. If you want to create a random matrix with numpy, you can just do:

num_rows = 3
num_columns = 3
random_matrix = numpy.random.random((num_rows, num_columns))

The result would be:

array([[ 0.15194989,  0.21977027,  0.85063633],
   [ 0.1879659 ,  0.09024749,  0.3566058 ],
   [ 0.18044427,  0.59143149,  0.25449112]])

You can also create a random matrix without numpy:

import random

num_rows = 3
num_columns = 3
random_matrix = [[random.random() for j in range(num_rows)] for i in range(num_columns)]

The result would be:

[[0.9982841729782105, 0.9659048749818827, 0.22838327707784145], 
[0.3524666409224604, 0.1918744765283834, 0.7779130503458696], 
[0.5239230720346117, 0.0224389713805887, 0.6547162177880549]]

Per the comments, I've added a function to convert a one dimensional array to a matrix:

def convert_to_matrix(arr, chunk_size):
    return [arr[i:i+chunk_size] for i in range(0, len(arr), chunk_size)]

arr = [1,2,3,4,5,6,7,8,9]
matrix = convert_to_matrix(arr, 3)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]] is the output

Upvotes: 0

Related Questions