Bind matrices / vectors in Python, as in MATLAB?

Let A, x, yand z- some vectors or matrices of appropriate size. Then in MATLAB you can easily build a "super matrix" B:

A = [1 2;3 4];
x = [4;5];
y = [1 2];
z = 4;
B = [A x;y z];

Conclusion:

>> B

B =

     1     2     4
     3     4     5
     1     2     4

What is the best way to achieve the same effect in NumPy?

+4
source share
3 answers

You can use numpy.block:

In [27]: a
Out[27]: 
array([[1, 2],
       [3, 4]])

In [28]: x
Out[28]: 
array([[4],
       [5]])

In [29]: y
Out[29]: array([1, 2])

In [30]: z
Out[30]: 4

In [31]: np.block([[a, x], [y, z]])
Out[31]: 
array([[1, 2, 4],
       [3, 4, 5],
       [1, 2, 4]])
+3
source

You can achieve this using the concatenation function . From the official documentation here you are a pretty understandable example:

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

np.concatenate((a, b), axis=0)
array([[1, 2],
       [3, 4],
       [5, 6]])

np.concatenate((a, b.T), axis=1)
array([[1, 2, 5],
       [3, 4, 6]])
+2
source

MATLAB:

In [166]: A = np.matrix('1 2;3 4')
     ...: x = np.matrix('4;5')
     ...: y = np.matrix('1 2')
     ...: z = np.matrix('4')
     ...: 
In [167]: A
Out[167]: 
matrix([[1, 2],
        [3, 4]])
In [168]: x
Out[168]: 
matrix([[4],
        [5]])
In [169]: y
Out[169]: matrix([[1, 2]])
In [170]: z
Out[170]: matrix([[4]])
In [171]: np.bmat('A x; y z')
Out[171]: 
matrix([[1, 2, 4],
        [3, 4, 5],
        [1, 2, 4]])

, , bmat .. MATLAB , Python. , np.matrix 2d, MATLAB.

:

In [173]: np.block([[A,x],[y,z]])
Out[173]: 
matrix([[1, 2, 4],
        [3, 4, 5],
        [1, 2, 4]])

block np.array:

In [174]: np.block([[A.A,x.A],[y.A,z.A]])
Out[174]: 
array([[1, 2, 4],
       [3, 4, 5],
       [1, 2, 4]])

Python/numpy:

In [181]: Aa = np.array([[1, 2],[3, 4]])
     ...: xa = np.array([[4],[5]])
     ...: ya = np.array([1, 2])
     ...: za = np.array([4])

In [187]: np.block([[Aa, xa],[ya, za]])
Out[187]: 
array([[1, 2, 4],
       [3, 4, 5],
       [1, 2, 4]])

block concatenate. , hstack vstack, .

In [190]: np.vstack([np.hstack([Aa, xa]),np.hstack([ya, za])])
Out[190]: 
array([[1, 2, 4],
       [3, 4, 5],
       [1, 2, 4]])

@Mad r_ c_. concatenate, [] ( getitem). 2d ( ):

In [214]: np.r_[np.c_[A, x], np.c_[y, z]]
Out[214]: 
matrix([[1, 2, 4],
        [3, 4, 5],
        [1, 2, 4]])

np.r_[np.c_[A.A, x.A], np.c_[y.A, z.A]] .

, 2d 1d, :

np.r_[np.r_['1,2', Aa, xa], np.r_['1,2', ya, za]]

'2' , 2d . , , .

:

np.concatenate([np.concatenate([Aa, xa], axis=1), 
                np.concatenate([ya[None,:], za[None,:]], axis=1)],
                axis=0)

While I am, another version:

np.r_['0,2', np.c_[Aa, xa], np.r_[ya, za]]

Eveything, which can perform hstack, vstack, r_and c_can do so quickly with concatenateand some size settings.

+1
source

Source: https://habr.com/ru/post/1693137/


All Articles