[Numpy-discussion] Quikest way to create a diagonal matrix ?
Joris De Ridder
Joris.DeRidder at ster.kuleuven.be
Wed Mar 26 11:21:38 EDT 2008
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
More information about the NumPy-Discussion
mailing list