1

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!

0

1 Answer 1

1

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, i.e. 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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer! I have tried to generate 'B' using your code:np.zeros(0, dtype=np.int). And then extract some part from matrix A using that empty matrix B. Compared with the empty matrix I used before, it's element are 'float64' type. It seems that the question is we have to transfer the dtype of matrix B from float64 to int32? Thx for your help!
Any int or bool type should work. If you actually want the dtype to be float64, using the matrix B for indexing won't make sense.
Thanks for your help! Really appreciate that!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.