I am trying to translate a piece of 'for' loop code from Matlab to Python. And there is one statement in this block: A[B]=C
. All those three A, B and C are matrices. In python, I need to write as A[B-1]=C
, because of the difference of index criteria between Matlab and Python. When B is non-empty, this statement goes well in python. However, if B is empty, this statement goes like this:
A11 = np.copy(A[:,B-1]) #Remind that B is an empty matrix, like B=np.array([0])
IndexError:arrays used as indices must be of integer (or boolean) type
Actually, if B is empty, what I want to have for matrix A11 is just another empty matrix. Definitely I can use a if block to define what matrix A11 should be when B is an empty matrix. But it will be too fussy because I have another 5 statement like this kind of using matrix as an index. Could you give me an example that shows me how to fix this problem? Thanks a lot!
B = np.array([0])
does not generate an empty matrix, it just converts the list [0]
into a numpy array.
I suppose you meant something like B = np.zeros(0)
(where the argument is a shape). Numpy's default is dtype =float64
but in order to use an array for indexing integer or boolean type is required. For a non-empty array with values that are in fact integers numpy figures out that it can just change the dtype
.
To fix your problem you can simply specify the dtype
(to int or boolean) when you initialize it, ie B = np.zeros(0, dtype=np.int)
works fine. A
will then be an 'empty matrix' in the sense that one of its shape dimensions is 0 - the others however do not change.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.