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?
The most literal copy of MATLAB notation is:
With string input like this
bmat
has to look up the corresponding variables in the workspace, and so on. It has a MATLAB like feel, but is awkward Python. Note thatnp.matrix
is always 2d, just like the original MATLAB.Using a more conventional nested list input:
block
also works withnp.array
objects:With proper Python/numpy syntax:
Internally
block
usesconcatenate
. I think it used to usehstack
andvstack
, now it works its way down recursively.@Mad asked about
r_
andc_
. Those are versions of theconcatenate
family that use a [] syntax (because they are actually class objects with agetitem
method). For the 2d matrix inputs, this works (and is relatively pretty):np.r_[np.c_[A.A, x.A], np.c_[y.A, z.A]]
also works.For the arrays that are a mix of 2d and 1d I have to use:
The string '2' tells it to expand the elements to 2d before concatenating. I haven't used that string argument much, and had to experiment before I got it right.
The last expression is doing:
While I'm at it, another version:
Eveything that
hstack
,vstack
,r_
andc_
can do can be done just as fast withconcatenate
and a few dimension adjustments.You can use
numpy.block
:You can achieve this by using the concatenate function. From the official documentation, here you are a pretty self-explanatory example: