2

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.

1
  • 1
    You did not read the np.append docs (carefully enough)! As documented it is flattening the inputs. np.append is not a clone of the list append. Don't try use it in the same way. Better yet don't use it at all. Too many pitfalls for the beginner. Commented Oct 31, 2020 at 16:22

3 Answers 3

2

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

    X = np.identity(8, dtype=int)
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

0

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))

1 Comment

I tried to use reshape but I got this ` ValueError: cannot reshape array of size 8 into shape (8,8)`.some other answer worked for me, so thanks u

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.