Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate matrices/vectors in Python like in MATLAB?

Let A, x, y and z be some vectors or matrices of appropriate size. Then in MATLAB one can build a "super matrix" B out of them very easily:

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

The output is:

>> B

B =

     1     2     4
     3     4     5
     1     2     4

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

like image 823
space_voyager Avatar asked Feb 04 '18 03:02

space_voyager


People also ask

How do you concatenate multiple matrices?

Concatenating Matrices You can also use square brackets to append existing matrices. This way of creating a matrix is called concatenation. For example, concatenate two row vectors to make an even longer row vector. To arrange A and B as two rows of a matrix, use the semicolon.

How do you concatenate 3 matrices in MATLAB?

You can use the square bracket operator [] to concatenate or append arrays. For example, [A,B] and [A B] concatenates arrays A and B horizontally, and [A; B] concatenates them vertically.

How do you concatenate two matrices of different dimensions in MATLAB?

Or you can use cell. For ex: a = [1,2;3,4]; b = ones(3,3); c = {a,b}; Like that you can put different matrix size in a same variable...

Is NumPy similar to MATLAB?

NumPy arrays are the equivalent to the basic array data structure in MATLAB. With NumPy arrays, you can do things like inner and outer products, transposition, and element-wise operations.


1 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]])
like image 169
Warren Weckesser Avatar answered Sep 20 '22 14:09

Warren Weckesser