Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a custom 4x4 array using NumPy?

I am new to Python and I am having a bit of trouble with the array functions. I want to make a 4 by 4 array which contains the numbers from 1 to 16.

I know that using np.zeros((4,4)) outputs a 4x4 array with all zeros. Using np.array(range(17)) I can get an array of the required numbers BUT not in the correct shape (4x4).

It must be fairly simple, surely? All comments are much appreciated.

like image 457
turnip Avatar asked Sep 23 '13 18:09

turnip


People also ask

How do I create an array in NumPy?

To create a NumPy array, you can use the function np.array() . All you need to do to create a simple array is pass a list to it. If you choose to, you can also specify the type of data in your list.

How do you make a 3x3 matrix in Python?

You can use numpy. First, convert your list into numpy array. Then, take an element and reshape it to 3x3 matrix.


1 Answers

The problem is that you are creating an array of 17 values (zero through 16), which can't be reshaped to 4x4. Instead:

>>> a = np.arange(1, 17).reshape(4,4)
>>> a
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12],
       [13, 14, 15, 16]])
like image 190
bogatron Avatar answered Oct 09 '22 17:10

bogatron