3

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?

1
  • 5
    What about numpy.random.randint(0, 5, size=(s,s))? Other approaches would be for example numpy.array(a).reshape((s,s)) (if a is flat = 1d). Commented Feb 3, 2018 at 0:30

2 Answers 2

4

Try

np.random.randint(0, 5, size=(s, s))
Sign up to request clarification or add additional context in comments.

Comments

0

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

4 Comments

That solution works perfectly for the question asked thanks! How would I modify that approach if my array was like a set of unique numbers 0 to n*n in a shuffled order. Is there a way to wrap an array into a numpy matrix?
@J.Doe If I'm understanding correctly, you want to take a shuffled one dimensional array and turn it into a numpy matrix? i.e. turn [4,3,2,1] into array([[4,3],[2,1]])
Sure that would accomplish it
@J.Doe Will add to my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.