# Putting together a larger matrix from smaller matrices

Matjaz Bezovnik mbezovnik at freenet.si
Tue Aug 25 17:37:09 CEST 2009

```On Tue, 25 Aug 2009 08:26:44 -0700, Scott David Daniels
<Scott.Daniels at Acm.Org> wrote:

>Matjaz Bezovnik wrote:
>
>If you are using numpy (which it sounds like you are):
>
>IDLE 2.6.2
> >>> import numpy as np
> >>> v = np.array([[0,1,2],[3,4,5],[6,7,8]], dtype=float)
> >>> v
>array([[ 0.,  1.,  2.],
>        [ 3.,  4.,  5.],
>        [ 6.,  7.,  8.]])
> >>> w = np.array([[10,11,12],[13,14,15],[16,17,18]], dtype=float)
> >>> w
>array([[ 10.,  11.,  12.],
>        [ 13.,  14.,  15.],
>        [ 16.,  17.,  18.]])
> >>> r = np.zeros((6,6))
> >>> r
>array([[ 0.,  0.,  0.,  0.,  0.,  0.],
>        [ 0.,  0.,  0.,  0.,  0.,  0.],
>        [ 0.,  0.,  0.,  0.,  0.,  0.],
>        [ 0.,  0.,  0.,  0.,  0.,  0.],
>        [ 0.,  0.,  0.,  0.,  0.,  0.],
>        [ 0.,  0.,  0.,  0.,  0.,  0.]])
> >>> r[:3,:3] = v
> >>> r
>array([[ 0.,  1.,  2.,  0.,  0.,  0.],
>        [ 3.,  4.,  5.,  0.,  0.,  0.],
>        [ 6.,  7.,  8.,  0.,  0.,  0.],
>        [ 0.,  0.,  0.,  0.,  0.,  0.],
>        [ 0.,  0.,  0.,  0.,  0.,  0.],
>        [ 0.,  0.,  0.,  0.,  0.,  0.]])
> >>> r[3:,3:] = w
> >>> r
>array([[  0.,   1.,   2.,   0.,   0.,   0.],
>        [  3.,   4.,   5.,   0.,   0.,   0.],
>        [  6.,   7.,   8.,   0.,   0.,   0.],
>        [  0.,   0.,   0.,  10.,  11.,  12.],
>        [  0.,   0.,   0.,  13.,  14.,  15.],
>        [  0.,   0.,   0.,  16.,  17.,  18.]])
> >>>
>
>In general, make the right-sized array of zeros, and at various points:
>and you can ssign to subranges of the result array:
>
>     N = 3
>     result = np.zeros((len(parts) * N, len(parts) * N), dtype=float)
>     for n, chunk in enumerate(parts):
>         base = n * 3
>         result[base : base + 3, base : base + 3] = chunk
>
>--Scott David Daniels
>Scott.Daniels at Acm.Org

Scott, thank you very much for the snippet.

It is exactly what I looked for; simple to read and obvious as to what
it does even a month later to a non-pythonist!

Matjaz

```