Home > Enterprise >  how to change some rows of matrices together?
how to change some rows of matrices together?

Time:06-11

is it possible to change some rows of matrices together? for example, I have a matrix 'a' like this :

a=np.array( [[1,2],[3,4],[5,6],[7,8]] )

and another matrix 'b' like this:

b=np.array( [[9,10],[11,12],[13,14],[15,16]] )  

now I want to change them from the third row. so 'a' and 'b' will be like this:

np.array( [[1,2],[3,4],[13,14],[15,16]] )  
np.array( [[9,10],[11,12],[5,6],[7,8]] )

could you help me to do this? thanks.

CodePudding user response:

np.vstack is your friend

new_a = np.vstack((a[:2,:], b[2:,:]))
new_b = np.vstack((b[:2,:], a[2:,:]))


array([[ 1,  2],
       [ 3,  4],
       [13, 14],
       [15, 16]])

array([[ 9, 10],
       [11, 12],
       [ 5,  6],
       [ 7,  8]])

CodePudding user response:

This also worked quite well for me, using np.concatenate:

import numpy as np

a = np.array( [[1,2],[3,4],[5,6],[7,8]] )
b = np.array( [[9,10],[11,12],[13,14],[15,16]] ) 

c = np.concatenate( (a[:2,:], b[2:,:]) )
d = np.concatenate( (b[:2,:], a[2:,:]) )
  • Related