# [Numpy-discussion] Generalize hstack/vstack --> stack; Block matrices like in matlab

Stefan Otte stefan.otte at gmail.com
Tue Sep 9 05:42:38 EDT 2014

```Hey,

@Josef, I wasn't aware of `bmat` and `np.asarray(np.bmat(....))` does
basically what I want and what I'm already using.

Regarding the Tetris problem: that never happened to me, but stack, as
Josef pointed out, can handle that already :)

I like the idea of removing the redundant square brackets:
stack([[a, b], [c, d]]) --> stack([a, b], [c, d])
However, if the brackets are there there is no difference between
creating a `np.array` and stacking arrays with `np.stack`.

If we want to get fancy and turn this PR into something bigger
I sometimes have arrays that look like:
AB0
0 C
Where 0 is a scalar but is supposed to fill the rest of the array.
Having something like 0 in there might lead to ambiguities though. What does
ABC
0D0
mean? One could limit the "filler" to appear only on the left or the right:
AB0
0CD
But even then the shape is not completely determined. So we could
require to have one row that only consists of arrays and determines
the shape. Alternatively we could have a keyword parameter `shape`:
stack([A, B, 0], [0, C, D], shape=(8, 8))

Colin, with `bmat` you can do what you're asking for. Directly taken
from the example:
>>> np.bmat('A,B; C,D')
matrix([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 4, 7, 8],
[5, 6, 9, 0]])

General question: If `bmat` already offers something like `stack`
should we even bother implementing `stack`? More code leads to more
bugs and maintenance work.

Best,
Stefan

On Tue, Sep 9, 2014 at 12:14 AM, cjw <cjw at ncf.ca> wrote:
>
> On 08-Sep-14 4:40 PM, Joseph Martinot-Lagarde wrote:
>> Le 08/09/2014 15:29, Stefan Otte a écrit :
>>> Hey,
>>>
>>> quite often I work with block matrices. Matlab offers the convenient notation
>>>
>>>       [ a b; c d ]
> This would appear to be a desirable way to go.
>
> Numpy has something similar for strings.  The above is neater.
>
> Colin W.
>>> to stack matrices. The numpy equivalent is kinda clumsy:
>>>
>>> vstack([hstack([a,b]), hstack([c,d])])
>>>
>>> I wrote the little function `stack` that does exactly that:
>>>
>>>       stack([[a, b], [c, d]])
>>>
>>> In my case `stack` replaced `hstack` and `vstack` almost completely.
>>>
>>> If you're interested in including it in numpy I created a pull request
>>> [1]. I'm looking forward to getting some feedback!
>>>
>>>
>>> Best,
>>>    Stefan
>>>
>>>
>>>
>>> [1] https://github.com/numpy/numpy/pull/5057
>>>
>> The outside brackets are redundant, stack([[a, b], [c, d]]) should be
>> stack([a, b], [c, d])
>>
>> _______________________________________________
>> NumPy-Discussion mailing list
>> NumPy-Discussion at scipy.org
>> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion

```