[Numpy-discussion] How do I make a diagonal matrix?

David Douard david.douard at logilab.fr
Fri Jun 23 10:08:26 CDT 2006


On Fri, Jun 23, 2006 at 07:55:47AM -0700, Keith Goodman wrote:
> On 6/23/06, Sven Schreiber <svetosch at gmx.net> wrote:
> > Keith Goodman schrieb:
> > > How do I make a NxN diagonal matrix with a Nx1 column vector x along
> > > the diagonal?
> > >
> >
> > >>> help(n.diag)
> > Help on function diag in module numpy.lib.twodim_base:
> >
> > 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.
> 
> I tried
> 
> >> x = rand(3,1)
> 
> >> diag(x)
> array([ 0.87113114])
> 
> Isn't rand(3,1) a vector?

No:
In [13]: rand(3).shape  
Out[13]: (3,)

In [14]: rand(3,1).shape
Out[14]: (3, 1)

A "vector" is an array with only one dimension. Here, you have a 3x1
"matrix"...

> 
> Off list I was given the example:
>  x=rand(3)
> diag(3)

So you've got the solution!

> That works. But my x is a Nx1 matrix. I can't get it to work with matrices.

???
Don't understand what you cannot make work, here.

In [15]: x=rand(3,1)     

In [18]: diag(x[:,0])
Out[18]: 
array([[ 0.2287158 ,  0.        ,  0.        ],
       [ 0.        ,  0.50571537,  0.        ],
       [ 0.        ,  0.        ,  0.72304857]])


What else would you like?

David


> Joris: The Numpy Example List looks good. I hadn't come across that before.
> 


David Douard                             LOGILAB, Paris (France)
Formations Python, Zope, Plone, Debian : http://www.logilab.fr/formations
Développement logiciel sur mesure :      http://www.logilab.fr/services
Informatique scientifique :              http://www.logilab.fr/science
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://projects.scipy.org/pipermail/numpy-discussion/attachments/20060623/5f3252e4/attachment-0001.bin 


More information about the Numpy-discussion mailing list