[SciPy-user] assign to diagonal values?

David Warde-Farley dwf@cs.toronto....
Wed Jan 30 21:44:42 CST 2008


On 30-Jan-08, at 10:08 PM, Alan G Isaac wrote:

> #diagrv: insert v as diagonal of matrix x (2D only!)
> def diagrv(x,v,copy=True):
> 	assert(len(x.shape)==2), "For 2-d arrays only."
> 	x = numpy.matrix( x, copy=copy )
> 	stride = 1 + x.shape[1]
> 	x.flat[ slice(0,None,stride) ] = v
> 	return x

Ooh that is clever.  This should really go on the Cookbook page.

Perhaps more generally, for in place modification:

def setdiag(m, d):
	assert(len(x.shape) == 2)
	stride = 1 + x.shape[1]
	m.flat[slice(0,None,stride)] = d


Regards,

David


More information about the SciPy-user mailing list