[Numpy-discussion] Functions for indexing into certain parts of an array (2d)

Keith Goodman kwgoodman@gmail....
Sat Jun 6 13:50:14 CDT 2009


On Sat, Jun 6, 2009 at 11:46 AM, Keith Goodman <kwgoodman@gmail.com> wrote:
> On Sat, Jun 6, 2009 at 11:30 AM, Fernando Perez <fperez.net@gmail.com> wrote:
>> On Sat, Jun 6, 2009 at 12:09 AM, Robert Kern<robert.kern@gmail.com> wrote:
>>> diag_indices() can be made more efficient, but these are fine.
>>
>> Suggestion?  Right now it's not obvious to me...
>
> I'm interested in a more efficient way too. Here's how I plan to adapt
> the code for my personal use:
>
> def fill_diag(arr, value):
>    if arr.ndim != 2:
>        raise ValueError, "Input must be 2-d."
>    idx = range(arr.shape[0])
>    arr[(idx,) * 2] = value
>    return arr

Maybe it is confusing to return the array since the operation is in place. So:

def fill_diag(arr, value):
    if arr.ndim != 2:
        raise ValueError, "Input must be 2-d."
    idx = range(arr.shape[0])
    arr[(idx,) * 2] = value


More information about the Numpy-discussion mailing list