[SciPy-user] assign to diagonal values?

Mclean Edwards mcleane@math.ubc...
Wed Jan 30 21:02:46 CST 2008


Hello,

m -= diag(m)
subtracts diag(m) from each row of m for me, if m is a numpy 
array, so your method could be far worse than wasteful.


There may be an easier way to implement, but at its root it will be 
similar to the simple for loop:

for i in range(len(new_diagonal)):
   m[i][i] = new_diagonal[i]

assuming that new_diagonal is already a 1D array.
If not, try:

new_diagonal = diag(new_diagonal)

first then run.

If your dimensions are (very) large,
you may have increased performance with

for i in xrange(len(new_diagonal)):

Hope this is helpful,

Mclean


On Wed, 30 Jan 2008, Carlos Scheidegger 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)
>
> but that seems pretty wasteful (especially if diag() creates new arrays, which
> I suspect it does). Is there a standard (or any efficient) way to assign the
> diagonal values directly without an explicit for loop? Googling for
> "site:www.scipy.org assign diagonal" only returned results for sparse
> matrices, which is not the case here - these are plain numpy arrays.
>
> Thanks in advance,
> -carlos
> _______________________________________________
> SciPy-user mailing list
> SciPy-user@scipy.org
> http://projects.scipy.org/mailman/listinfo/scipy-user
>


More information about the SciPy-user mailing list