[SciPy-user] assign to diagonal values?

Anne Archibald peridot.faceted@gmail....
Thu Jan 31 00:37:21 CST 2008


On 30/01/2008, Carlos Scheidegger <cscheid@sci.utah.edu> wrote:
> Say I have a matrix m whose diagonal values I want to replace with the
> contents of vector new_diagonal. Right now, I'm using
>
> m -= diag(m)
> m += diag(new_diagonal)

If m is n by n, how about this?

m[range(n),range(n)]=new_diagonal

Slightly less efficient than using strides as suggested elsewhere if
the array is contiguous in memory, but it'll work no matter how m is
laid out and it's clear. It also generalizes, of course.

(Incidentally, if it seems like this should set all elements of m,
this is what I would have thought too, but it's not how numpy works.
For that use the N._ix function.)

Anne


More information about the SciPy-user mailing list