1

How do I create an numpy array of shape (120,120), with the first 7 values being 0.924 and the rest of the values being 0.53.I need this for a matrix in matplotlib

1
  • This question it's not strictly related to matplotlib. Tag removed Commented Apr 9, 2013 at 11:57

2 Answers 2

3

The fastest way is probably to create an empty array, fill it with a constant value, and update the few values that need to be updated:

>>> x = np.empty((120, 120))
>>> x.fill(0.53)
>>> x[0,:7] = 0.924
>>> x
array([[ 0.924,  0.924,  0.924, ...,  0.53 ,  0.53 ,  0.53 ],
       [ 0.53 ,  0.53 ,  0.53 , ...,  0.53 ,  0.53 ,  0.53 ],
       [ 0.53 ,  0.53 ,  0.53 , ...,  0.53 ,  0.53 ,  0.53 ],
       ..., 
       [ 0.53 ,  0.53 ,  0.53 , ...,  0.53 ,  0.53 ,  0.53 ],
       [ 0.53 ,  0.53 ,  0.53 , ...,  0.53 ,  0.53 ,  0.53 ],
       [ 0.53 ,  0.53 ,  0.53 , ...,  0.53 ,  0.53 ,  0.53 ]])
Sign up to request clarification or add additional context in comments.

Comments

0
--> x = np.array([0.53]*(120*120)).reshape(120,120)
--> x[0,:7] = 0.924

Will fill the first 7 values in the first row as 0.924, swap the 0 and :7 in the index to get the first 7 in the first column as 0.924

2 Comments

Don't do this! You are creating a 14,400 item long Python list, which is then parsed by numpy to find out its length and dtype, allocate an array and then copy the list data into it. See @EOL's answer for the better approach to this.
While @Jaime is right about why this approach is relatively slow, I must say that it has the advantage of being a quite legible one-liner; I would use it if speed is not too much of a concern. A similar, and probably faster one-line solution would be x = np.ones((120, 120))*0.53. (The fastest of the three is that of my answer, as it only involves simple and fast value settings.)

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.