[Numpy-discussion] Functions for indexing into certain parts of an array (2d)
Bruce Southey
bsouthey at gmail.com
Sat Jun 6 16:31:27 EDT 2009
On Sat, Jun 6, 2009 at 2:01 AM, Fernando Perez<fperez.net at gmail.com> wrote:
[snip]
> ####
>
> def mask_indices(n,mask_func,k=0):
> """Return the indices for an array, given a masking function like
> tri{u,l}."""
> m = np.ones((n,n),int)
> a = mask_func(m,k)
> return np.where(a != 0)
>
>
> def diag_indices(n,ndim=2):
> """Return the indices to index into a diagonal.
>
> Examples
> --------
> >>> a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
> >>> a
> array([[ 1, 2, 3, 4],
> [ 5, 6, 7, 8],
> [ 9, 10, 11, 12],
> [13, 14, 15, 16]])
> >>> di = diag_indices(4)
> >>> a[di] = 100
> >>> a
> array([[100, 2, 3, 4],
> [ 5, 100, 7, 8],
> [ 9, 10, 100, 12],
> [ 13, 14, 15, 100]])
> """
> idx = np.arange(n)
> return (idx,)*ndim
>
>
While not trying to be negative, this raises important questions that
need to be covered because the user should not have to do trial and
error to find what actually works and what that does not. While
certain features can be fixed within Numpy, API changes should be
avoided.
Please explain the argument of 'n'?
Since you seem to be fixing it to the length of the main diagonal then
it is redundant. Otherwise why the first 'n' diagonal elements and not
the last 'n' diagonal elements. If it meant to be allow different
diagonal elements then it would need adjustment to indicate start and
stopping location.
What happens when the shape of 'a' is different from 'n'? I would
think that this means that diag_indices should be an array method or
require passing a (or shape of a to diag_indices).
What happens if the array is not square? If a is 4 by 2 then passing
n=4 will be wrong.
What about offdiagonals? That is should be clear that you are
referring to the main diagonal.
How does this address non-contiguous memory, Fortran ordered arrays
or arrays with more than 2 dimensions?
How does this handle record and masked arrays as well as the matrix
subclass that are supported by Numpy? Presumably it does not so if it
is not an array method, then the type of input would need to be
checked.
There are probably similar issues to the other functions you propose.
Bruce
More information about the NumPy-Discussion
mailing list