lskrinjar
lskrinjar

Reputation: 5793

How to create a numpy matrix/2d array from multiple 2d arrays?

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

Upvotes: 1

Views: 842

Answers (2)

tom10
tom10

Reputation: 69182

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.]]

Upvotes: 1

YXD
YXD

Reputation: 32511

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.        ]])
>>>

Upvotes: 1

Related Questions