-1

I have a matrix and I want to add a vector into the fourth row of the matrix. I am using vstack but I am having trouble figuring out how to input it as the fourth row. If I input the new vector as either the first or second argument, it will add the vector as the first or last row of them matrix. Here is my example:

A = np.reshape(range(1,21),(4,5)
print (A)
B = np.vstack([(10,3,5,2,6),A])
print(B)

With this code, B will have the new vector as the first row of the matrix. I need it to be the fourth row so that when I print B, the last row of the matrix is [16,17,18,19,20] and B becomes a 5x5 matrix.

[1  2  3  4  5]
[6  7  8  9  10]
[11 12 13 14 15]
[10 3  5  2  6]
[16 17 18 19 20]

The matrix above is my desired output. What do I need to include?

camaya3
  • 57
  • 4
  • Please provide the desired result for the included example explicitly, *add a vector into the fourth row* is ambiguous in several ways. – Michael Szczesny Oct 28 '22 at 21:00
  • Does this answer your question? [Inserting a row at a specific location in a 2d array in numpy?](https://stackoverflow.com/questions/8298797/inserting-a-row-at-a-specific-location-in-a-2d-array-in-numpy) – Michael Szczesny Oct 28 '22 at 21:39
  • `vstack` 3 rows of A, B, and the last row of A – hpaulj Oct 29 '22 at 05:18

1 Answers1

2

I think this should do it. Likely read the docs to get clarification, but this seemed to work.

B = np.vstack([A, (10,3,5,3,6)])

for some reason the order mattered, of course I did not read enough to give more.

grifway
  • 59
  • 5