1

In python I would like to build a matrix from four 2d numpy arrays

m = np.eye(3, 3)
c = np.random.rand(2, 3)
cT = c.T
z = np.zeros([min(np.shape(c)), min(np.shape(c))])

and the new matrix shape is defined as:

[[m, cT],
 [c, z]]

or like this (with numerical data):

1.      0.      0.      0.0109  0.5339
0.      1.      0.      0.4991  0.9854
0.      0.      1.      0.5942  0.7565
0.0109  0.4991  0.5942  0.      0.
0.5339  0.9854  0.7565  0.      0.

I would like to ask you what would be the easiest was and also the quickest (CPU-wise) in python using numpy

2 Answers 2

1

The most straightforward way is to copy each piece of data across to the appropriate slice

>>> m = np.eye(3, 3)
>>> c = np.random.rand(2, 3)
>>> cT = c.T
>>> z = np.empty([min(np.shape(c)), min(np.shape(c))])
>>> X = np.eye(5, 5)
>>> X[:3, :3] = m
>>> X[:3, -2:] = c.T
>>> X[-2:, :3] = c
>>> X[-2:, -2:] = z
>>> X
array([[ 1.        ,  0.        ,  0.        ,  0.98834141,  0.69806125],
       [ 0.        ,  1.        ,  0.        ,  0.97342311,  0.97368278],
       [ 0.        ,  0.        ,  1.        ,  0.28701318,  0.08705423],
       [ 0.98834141,  0.97342311,  0.28701318,  0.        ,  0.        ],
       [ 0.69806125,  0.97368278,  0.08705423,  0.        ,  0.        ]])
>>>
Sign up to request clarification or add additional context in comments.

1 Comment

Nice! I haven't tested it (both solutions), but I think that this is a faster (time, CPU - wise) way than the one with hstack and vstack. My solution was with numpy.concatenate.
1

Combining vstack and hstack can do this:

from numpy import ones, hstack, vstack
a, b, c, d = ones((3,3)), 2*ones((3,2)), 3*ones((2,3)), 4*ones((2,2))

x = hstack(( vstack((a, c)), vstack((b, d)) ))

[[ 1.  1.  1.  2.  2.]
 [ 1.  1.  1.  2.  2.]
 [ 1.  1.  1.  2.  2.]
 [ 3.  3.  3.  4.  4.]
 [ 3.  3.  3.  4.  4.]]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.