0

Is there any more concise syntax to stack array/matrix? In MatLab, you can simply do [x, y] to stack horizontally, and [x; y] to stack vertically, and it can be easily chained, such as [x, x; y, y]; while in python, it seems to be more tedious, see below:

import numpy as np
x = np.array([[1, 1, 1], [1, 2, 3]])
y = x*10
np.vstack((x, y))

array([[ 1,  1,  1],
       [ 1,  2,  3],
       [10, 10, 10],
       [10, 20, 30]])

np.hstack((x, y))

array([[ 1,  1,  1, 10, 10, 10],
       [ 1,  2,  3, 10, 20, 30]])

np.vstack((np.hstack((x, x)), np.hstack((y, y))))

array([[ 1,  1,  1,  1,  1,  1],
       [ 1,  2,  3,  1,  2,  3],
       [10, 10, 10, 10, 10, 10],
       [10, 20, 30, 10, 20, 30]])
2
  • I don't think that this is possible as there is no python syntax for something like this Commented Jan 28, 2018 at 7:51
  • 1
    You may also want to look at np.r_ and np.c_. Commented Jan 28, 2018 at 8:32

1 Answer 1

2

MATLAB has its own interpreter, so it can interpret the ; etc to suit its needs. numpyuses the Python interpreter, so can't use or reuse basic syntactic characters like [],;. So the basic array constructor wraps a nested list of lists (takes a list as argument):

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

But that nesting can be carried to any depth, np.array([]), np.array([[[[['foo']]]]]), because arrays can have 0,1, 2 etc dimensions.

MATLAB initially only had 2d matrices, and still can't have 1 or 0d.

In MATLAB that matrix is the basic object (cell and struct came later). In Python lists are the basic object (with tuples and dicts close behind).

np.matrix takes a string argument that imitates the MATLAB syntax. np.matrix('1 2; 3 4'). But np.matrix like the original MATLAB is fixed at 2d.

https://docs.scipy.org/doc/numpy/reference/arrays.classes.html#matrix-objects

https://docs.scipy.org/doc/numpy/reference/generated/numpy.bmat.html#numpy.bmat

But seriously, who makes real, useful matrices with the 1, 2; 3, 4 syntax? Those are toys. I prefer to use np.arange(12).reshape(3,4) if I need a simple example.

numpy has added a np.stack which gives more ways of joining arrays into new constructs. And a np.block:

https://docs.scipy.org/doc/numpy/reference/generated/numpy.block.html#numpy.block

Sign up to request clarification or add additional context in comments.

Comments

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.