2

Is there a way to make a NxN array (so 2d array) of elements, where each element is an array of 3 numbers randomly chosen between 0 and 1?

Output should look something like this:

(0.2,0.45,0.98), (0.7,0.58,0.11) ...
(1.0,0.05,0.63, ...
.
.
.

etc.

I've been trying to do this but there must be a more elegant way. Code included below:

import numpy as  np
import matplotlib.pyplot as plt

lat = []

for _ in range(2):

        w = []

        for _ in range(2):
                a = np.random.uniform(0.0,1.0)
                b = np.random.uniform(0.0,1.0)
                c = np.random.uniform(0.0,1.0)

                D = np.array([a,b,c])

                w.append(D)

        lat.append(w)

        if _ >= 1:
                np.hstack(lat)

2 Answers 2

1

You can use numpy.random.rand where the first argument is the number of rows you want to generate, then the second argument can be 3 in your case for each row.

>>> import numpy as np
>>> np.random.rand(10,3)
array([[ 0.80325895,  0.70250496,  0.4256057 ],
       [ 0.28863352,  0.14066084,  0.08918333],
       [ 0.52669678,  0.07641594,  0.92869148],
       [ 0.40105226,  0.88909989,  0.25459293],
       [ 0.8202674 ,  0.34435551,  0.49131868],
       [ 0.14251546,  0.51029693,  0.54037975],
       [ 0.07118544,  0.95467079,  0.87722367],
       [ 0.33530285,  0.64395738,  0.8289817 ],
       [ 0.5461907 ,  0.93165573,  0.73256816],
       [ 0.31204938,  0.38230589,  0.49739997]])
Sign up to request clarification or add additional context in comments.

1 Comment

So if i use: np.random.rand(3,3,3) That gives me the matrix I described in the question but with the three elements going into the 3rd dimension so it's like a data cube. Thank you CoryKramer!
1

You can use numpy.reshape to reshape randomly generated numbers.

>>> N = 3
>>> np.random.rand(N*N*3).reshape([N,N,3])
array([[[ 0.48513983,  0.49582462,  0.96211702],
        [ 0.95061997,  0.63674441,  0.51228963],
        [ 0.06988701,  0.9018317 ,  0.63418989]],

       [[ 0.31213247,  0.75325276,  0.04600117],
        [ 0.23449785,  0.04731562,  0.89007085],
        [ 0.25746369,  0.96337201,  0.6032985 ]],

       [[ 0.2207508 ,  0.43560328,  0.75067189],
        [ 0.84054857,  0.28190793,  0.08875157],
        [ 0.00419059,  0.13464854,  0.63074635]]])

Result is a 2d array of array of 3 numbers.

>>> temp = np.random.rand(N*N*3).reshape([N,N,3])
>>> temp[0][0]
array([ 0.48513983,  0.49582462,  0.96211702])

Comments

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.