I want to preallocate an integer matrix to store indices generated in iterations. In MATLAB this can be obtained by IXS = zeros(r,c)
before for
loops, where r
and c
are number of rows and columns. Thus all indices in subsequent for
loops can be assigned into IXS
to avoid dynamic assignment. If I accidentally select a 0 in my codes, for example, a wrong way to pick up these indices to select elements from a matrix, error can arise.
But in numpy, 0 or other minus values can also be used as indices. For example, if I preallocate IXS
as IXS=np.zeros([r,c],dtype=int)
in numpy. In a for
loop, submatrix specified by the indices assigned into IXS
previously can be obtained by X(:,IXS(IXS~=0))
in MATLAB, but the first row/column may be lost if I perform the selection in the same way in numpy.
Further, in a large program with operations of large matrices, preallocation is important in speeding up the computation, and it is easy to locate the error raised by wrong indexing as 0 may be selected in MATLAB. In numpy, if I select an array by for example X[:,IXS[:n]]
with wrong n
, no error occurs. I have to pay lots of times to check where the error is. More badly, if the final results are not so strange, I may ignore this bug. This always occurs in my program. Thus I have to debug my codes again and again.
I wonder is there a safe way to preallocate such index matrix in numpy?