Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 , Numpy -- Matrix of Matrix elements

I want to create a matrix that contains matrix elements. So I did the obvious thing and made this:

import numpy as np

A = np.array([1,2,3,1],[3,1,5,1])
B = np.array([1,6,8,9],[9,2,7,1])
E = np.array([A, B],[B, A])

But the compiler returns: TypeError: data type not understood

What can I do to create such a matrix, because I have really huge matrices and I dont have the time to explicitly write everyone down ?


* Edit 1: *

Additional problem that occurred:

enter image description here

Instead of getting a 14x14 matrix, I am getting a multidimensional (2,2,7,7) matrix. Where in the simplified version that was my original question , everything is sound. Any ideas why this occurs now?

In this case I have the Amat 7x7, Bmat 7x7 , Emat 14x14, Smat 14x14


Edit 2

Ok I solved the problem using the np.block() as it was stated in the comments below. Thank you very much.


like image 779
GeometricalFlows Avatar asked Feb 15 '26 03:02

GeometricalFlows


1 Answers

Assuming that you want a two-dimensional array of shape (4, 8) as a result, it sounds as though you're looking for numpy.block. It's available since NumPy 1.13, and as the name suggests, it creates a new array out of blocks, where each block is an existing array.

You also need an extra pair of square brackets in the calls that create A and B. The signature of numpy.array is:

array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)

So if you write np.array([1, 2, 3, 1], [3, 1, 5, 1]) then you're passing two arguments to the array function, and the second argument will be interpreted as the dtype: i.e., the desired datatype of the elements of the array. This is why you're getting the "data type not understood" error. Instead, you want to pass a nested list-of-lists as the first argument: np.array([[1, 2, 3, 1], [3, 1, 5, 1]]).

Putting it all together:

>>> import numpy as np
>>> A = np.array([[1, 2, 3, 1], [3, 1, 5, 1]])
>>> B = np.array([[1, 6, 8, 9], [9, 2, 7, 1]])
>>> E = np.block([[A, B], [B, A]])
>>> A
array([[1, 2, 3, 1],
       [3, 1, 5, 1]])
>>> B
array([[1, 6, 8, 9],
       [9, 2, 7, 1]])
>>> E
array([[1, 2, 3, 1, 1, 6, 8, 9],
       [3, 1, 5, 1, 9, 2, 7, 1],
       [1, 6, 8, 9, 1, 2, 3, 1],
       [9, 2, 7, 1, 3, 1, 5, 1]])
like image 147
Mark Dickinson Avatar answered Feb 17 '26 16:02

Mark Dickinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!