# [Numpy-discussion] Quikest way to create a diagonal matrix ?

lorenzo bolla lbolla@gmail....
Wed Mar 26 11:23:40 CDT 2008

```I like obfuscating things! Maybe I should switch to perl :-)
you can use a one-liner like this:

scipy.linalg.triu(z) + scipy.linalg.triu(z,k=1).T

my %timeit gives roughly the same execution speed as your f(z):

In [79]: %timeit f(z)
10000 loops, best of 3: 79.3 us per loop

In [80]: %timeit h(z)
10000 loops, best of 3: 76.8 us per loop

L.

On Wed, Mar 26, 2008 at 4:21 PM, Joris De Ridder <
Joris.DeRidder@ster.kuleuven.be> wrote:

>
> On 26 Mar 2008, at 15:36, lorenzo bolla wrote:
>
> > numpy.tri
> >
> > In [31]: T = numpy.tri(m)
> >
> > In [32]: z.T * T + z * T.T
> > Out[32]:
> > array([[  0.,   1.,   2.,   3.,   4.],
> >        [  1.,  12.,   7.,   8.,   9.],
> >        [  2.,   7.,  24.,  13.,  14.],
> >        [  3.,   8.,  13.,  36.,  19.],
> >        [  4.,   9.,  14.,  19.,  48.]])
>
>
> You still have to subtract the diagonal:
>
> def f(z):
>     A = tri(z.shape[0], dtype = z.dtype)
>     X = z.T * A + z * A.T
>     X[range(A.shape[0]),range(A.shape[0])] -= z.diagonal()
>     return X
>
>
> The suggestion of Alexandre seems to be about 4 times as fast, though.
>
> But I love the way you obfuscate things by having "T" for both the tri-
> matrix as the transpose method. :-)
> It get's even better with numpy matrices. Next year, my students will
> see something like
> I.H-T.H*T.I+I.I*H.I+T.T*H.H-H.I
> Refreshing! ;-)
>
> Cheers,
> Joris
>
>
> Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm
>
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion@scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>

--
Lorenzo Bolla
lbolla@gmail.com
http://lorenzobolla.emurse.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20080326/fa6fa6bb/attachment.html
```