18

I have a simple, one dimensional Python array with random numbers. What I want to do is convert it into a numpy Matrix of a specific shape. My current attempt looks like this:

randomWeights = []
for i in range(80):
    randomWeights.append(random.uniform(-1, 1))
W = np.mat(randomWeights)
W.reshape(8,10)

Unfortunately it always creates a matrix of the form:

[[random1, random2, random3, ...]]

So only the first element of one dimension gets used and the reshape command has no effect. Is there a way to convert the 1D array to a matrix so that the first x items will be row 1 of the matrix, the next x items will be row 2 and so on?

Basically this would be the intended shape:

[[1, 2, 3, 4, 5, 6, 7, 8],
 [9, 10, 11, ... ,    16],
 [...,               800]]

I suppose I can always build a new matrix in the desired form manually by parsing through the input array. But I'd like to know if there is a simpler, more eleganz solution with built-in functions I'm not seeing. If I have to build those matrices manually I'll have a ton of extra work in other areas of the code since all my source data comes in simple 1D arrays but will be computed as matrices.

2
  • Why is there the number 800 in the last element, and not 80? Commented Sep 17, 2019 at 17:28
  • Don't forget import random Commented Sep 17, 2019 at 17:37

2 Answers 2

28

reshape() doesn't reshape in place, you need to assign the result:

>>> W = W.reshape(8,10)
>>> W.shape
(8,10)    
Sign up to request clarification or add additional context in comments.

1 Comment

It should be reshape(10,8) for the intended 10 x 8 matrix, btw
2

You can use W.resize(), ndarray.resize()

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.