[Numpy-discussion] How do I make a diagonal matrix? (original) (raw)

Alan G Isaac aisaac at american.edu
Fri Jun 23 11:50:13 EDT 2006


On Fri, 23 Jun 2006, Sven Schreiber apparently wrote:

help(n.diag) Help on function diag in module numpy.lib.twodimbase: diag(v, k=0) returns the k-th diagonal if v is a array or returns a array with v as the k-th diagonal if v is a vector.

That is pretty damn obscure. Apparently Travis's new doc string did not survive? The Numpy book says: diag (v, k=0) Return the kth diagonal if v is a 2-d array, or returns 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=0) 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 (and zeros elsewhere).

fwiw, Alan Isaac

PS As a response to the question, it might be worth noting the following.

y=N.zeros((5,5)) values=N.arange(1,6) indices=slice(0,25,6) y.flat[indices]=values 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=True): if copy: x = numpy.matrix( x, copy=True ) else: x = numpy.matrix( x, copy=False ) stride = 1 + x.shape[1] x.flat[ slice(0,x.size,stride) ] = v return x



More information about the NumPy-Discussion mailing list