2

I would like to have a numpy matrix that is filled with unique objects. Currently I am creating a list of list and then converting it to a numpy array (see code below, under workaround). I am using it because I want to use slicing to access elements in the matrix

I was wondering if there was a better way to create such a matrix.

import random
import numpy as np

class RandomCell(object):
    def __init__(self):
        self.value = random.randint(0, 10)
    def __repr__(self):
        return str(self.value)

# workaround
temp_matrix = [[RandomCell() for row in range(3)] for col in range(3)]
workaround_matrix = np.array(temp_matrix)

EDIT: I want to create a matrix of objects not generate a matrix of random numbers

2 Answers 2

3

Your method of building the array from a list of lists is fine. Another option would be

arr = np.array([RandomCell() for item in range(9)]).reshape(3,3)

Usually, to save memory you could use np.fromiter to build an array from an iterator. However, since this array has dtype object, unfortunately np.fromiter is not an option in this case.

Sign up to request clarification or add additional context in comments.

Comments

1

That's actually really simple

import numpy as np
np.random.randint(0, 10, (3,3))

1 Comment

I want to create objects. not generate random numbers. my apologies

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.