简体   繁体   中英

how to create a numpy matrix of 8*8

I am trying to make a matrix of 8*8, so i used this:

s=np.indices((8,8))

output:

array([[[0, 0, 0, 0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1, 1, 1, 1],
        [2, 2, 2, 2, 2, 2, 2, 2],
        [3, 3, 3, 3, 3, 3, 3, 3],
        [4, 4, 4, 4, 4, 4, 4, 4],
        [5, 5, 5, 5, 5, 5, 5, 5],
        [6, 6, 6, 6, 6, 6, 6, 6],
        [7, 7, 7, 7, 7, 7, 7, 7]],

       [[0, 1, 2, 3, 4, 5, 6, 7],
        [0, 1, 2, 3, 4, 5, 6, 7],
        [0, 1, 2, 3, 4, 5, 6, 7],
        [0, 1, 2, 3, 4, 5, 6, 7],
        [0, 1, 2, 3, 4, 5, 6, 7],
        [0, 1, 2, 3, 4, 5, 6, 7],
        [0, 1, 2, 3, 4, 5, 6, 7],
        [0, 1, 2, 3, 4, 5, 6, 7]]])

However, I just want a single matrix that looks like the first one.

Lots of ways to do this:

  1. Take the first element of your np.indices() result
np.indices((8,8))[0]
  1. Repeat / tile the result of np.arange()
np.tile(np.arange(8), (8, 1)).T
  1. Create an 8x8 array of zeros and add a column vector containing the numbers 0-7. Let broadcasting take care of the rest
np.zeros((8, 8)) + np.arange(8)[:, None]
# or 
(np.zeros((8, 8)) + np.arange(8)).T
  1. Multiply a 8x1 column vector containing the numbers 0-7 with a row vector of eight ones. Also uses broadcasting
np.arange(8)[:, None] * np.ones((1, 8))
# or 
(np.ones((8, 1)) * np.arange(8)).T

All of these give the same result (save for dtype -- the first two return int arrays, the rest return float arrays, but changing the type is pretty easy anyway):

array([[0., 0., 0., 0., 0., 0., 0., 0.],
       [1., 1., 1., 1., 1., 1., 1., 1.],
       [2., 2., 2., 2., 2., 2., 2., 2.],
       [3., 3., 3., 3., 3., 3., 3., 3.],
       [4., 4., 4., 4., 4., 4., 4., 4.],
       [5., 5., 5., 5., 5., 5., 5., 5.],
       [6., 6., 6., 6., 6., 6., 6., 6.],
       [7., 7., 7., 7., 7., 7., 7., 7.]])

Finding which is the most efficient is left as an exercise for the reader.

try something like this ?

import numpy as np

zeors_array = np.zeros( (8, 8) )
print(zeors_array)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM