From: Alan G I. <ai...@am...> - 2006-06-23 15:42:41
|
On Fri, 23 Jun 2006, Sven Schreiber apparently wrote:=20 >>>> help(n.diag)=20 > Help on function diag in module numpy.lib.twodim_base:=20 > diag(v, k=3D0)=20 > returns the k-th diagonal if v is a array or returns a array=20 > with v as the k-th diagonal if v is a vector.=20 That is pretty damn obscure. Apparently Travis's new doc string did not survive? The Numpy book says: diag (v, k=3D0) Return the kth diagonal if v is a 2-d array, or returns=20 an array with v as the kth diagonal if v is a 1-d array. That is better but not great. I think what is wanted is: diag (v, k=3D0) If v is a 2-d array: return a copy of the kth diagonal of v (as a 1-d array). If v is a 1-d array: return a 2-d array with a copy of v as the kth diagonal=20 (and zeros elsewhere). fwiw, Alan Isaac PS As a response to the question, it might be worth noting=20 the following. >>> y=3DN.zeros((5,5)) >>> values=3DN.arange(1,6) >>> indices=3Dslice(0,25,6) >>> y.flat[indices]=3Dvalues >>> y array([[1, 0, 0, 0, 0], [0, 2, 0, 0, 0], [0, 0, 3, 0, 0], [0, 0, 0, 4, 0], [0, 0, 0, 0, 5]]) Generalizing we end up with the following (from pyGAUSS): def diagrv(x,v,copy=3DTrue): =09if copy: x =3D numpy.matrix( x, copy=3DTrue ) =09else: x =3D numpy.matrix( x, copy=3DFalse ) =09stride =3D 1 + x.shape[1] =09x.flat[ slice(0,x.size,stride) ] =3D v return x |