generating to generate numpy array

Viewed 47

I am trying to generate a set of an array using the code below.I will try to explain what I have done too

First:

example = np.zeros(8,dtype=int)
print(example)

which gave me output: [0 0 0 0 0 0 0 0]

then:

input=np.array([],int)
for i in range(0,8):
  if i <8:
    example[i-1]=0
    example[i]=1
    print(example)
  input = np.append(input,example)
print(input)

which then gave me:

[0 1 0 0 0 0 0 0]
[0 0 1 0 0 0 0 0]
[0 0 0 1 0 0 0 0]
[0 0 0 0 1 0 0 0]
[0 0 0 0 0 1 0 0]
[0 0 0 0 0 0 1 0]
[0 0 0 0 0 0 0 1]

and atlast i do this input = np.append(input,example) which gives me: [1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1] but here's how I want this:

[[1 0 0 0 0 0 0 0]
[0 1 0 0 0 0 0 0]
[0 0 1 0 0 0 0 0]
[0 0 0 1 0 0 0 0]
[0 0 0 0 1 0 0 0]
[0 0 0 0 0 1 0 0]
[0 0 0 0 0 0 1 0]
[0 0 0 0 0 0 0 1]] 

or something like that. now, I tried to search, I get errors for whatever I try.hope I get as soon as possible.

3 Answers

If I understand your question correctly you're after the identity matrix.

    X = np.identity(8, dtype=int)

You can reshape the array with .reshape() (don't use input as variable name, here myInput should be your input variable):

myInput = myInput.reshape(8,8)

Also you can shorten it using np.identity:

myInput = np.identity(8, dtype=int)

To finish your attempt, you should write input = np.append(input,example).reshape(8,8). Alternatively, you can directly generate the desired output using out = np.diag(np.ones(8))

Related