Reputation: 1258
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]])
Upvotes: 0
Views: 1116
Reputation: 231530
MATLAB has its own interpreter, so it can interpret the ;
etc to suit its needs. numpy
uses 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
Upvotes: 2