Reputation: 14836
I was wondering if it was possible to create a nested matrix in python. Here I define my matrix A
A = array([[ 12., 0.],[ 0., 4.]])
I would like to replace the zeros with a generic 2x2 matrix and then plot everything with imshow()
. Is that possible?
I tried defining my nested matrix this way
A = array([[ 12., array([[ 1., 1.],[ 1., 1.]])],[ 0., 4.]])
but I got this error message
ValueError: setting an array element with a sequence.
Upvotes: 1
Views: 3229
Reputation: 70058
>>> M = NP.empty((5, 5), dtype=NP.object) # a 2D NumPy array
>>> M
array([[None, None, None, None, None],
[None, None, None, None, None],
[None, None, None, None, None],
[None, None, None, None, None],
[None, None, None, None, None]], dtype=object)
Now you can insert sequences, without getting the ValueError
>>> M[2,2] = NP.array([4, 3, 5])
>>> M
array([[None, None, None, None, None],
[None, None, None, None, None],
[None, None, [4 3 5], None, None],
[None, None, None, None, None],
[None, None, None, None, None]], dtype=object)
>>> M[2,2]
array([4, 3, 5])
The other part of the OP--passing an Array like this to Matplotlib's imshow, is a problem.
imshow visually represents a 2D array as a cloud of points positioned on the canvas according to their x, y indices. The value at that index is indicated according to different colors and color intensities based on a colormap which maps color to array value. Therefore, valid arguments for imshow's data parameter are:
NumPy arrays of higher dimension in two (and only these two AFAIK) which imshow can interpret as
NumPy 2D array of rgb tuples (x, y, r, b, g)
NumPy 6D arrays, which are interpreted as a 2D array of rgba tuples (x, y, r, g, b, a)
Upvotes: 2
Reputation: 7304
A numpy array has a data-type. In your first line you create A
such that:
import numpy as np
A = np.array([[ 12., 0.],[ 0., 4.]])
A.dtype
will print dtype('float64')
. That is everything you want to put inside such an array must be able to be interpreted as floats.
In you second creation of A this is probably the issue. If you instead do:
A = np.array([[ 12., np.array([[ 1., 1.],[ 1., 1.]])],[ 0., 4.]], dtype=np.object)
it will be created, however mind that A
has the shape 2x2. You should also realize that arrays must have regular size for all dimensions (there can't be any holes in arrays). That is, each position in the array is treated as a single object (some of which happen to be arrays themselves).
Now that will still not work to show with imshow
since it expects a 2D array with elements that can be interpreted as numbers and your A[0,1]
, for example, is an array itself with size 2x2. It can't be interpreted as a number.
So you should design your array A so that it is a 2D array of floats if you want to show it as an image with matplotlib.pyplot.imshow
and figure out how you wish to get your data into that structure.
Upvotes: 0