[Numpy-discussion] Quikest way to create a symetric (diagonal???) matrix ?

Alexandre Fayolle alexandre.fayolle at logilab.fr
Wed Mar 26 10:22:06 EDT 2008


On Wed, Mar 26, 2008 at 09:48:02AM -0400, Pierre GM wrote:
> All,
> What's the quickest way to create a diagonal matrix ? I already have the 
> elements above the main diagonal. Of course, I could use loops:
> >>>m=5
> >>>z = numpy.arange(m*m).reshape(m,m)
> >>>for k in range(m):
> >>>    for j in range(k+1,m):
> >>>        z[j,k] = z[k,j]
> But I was looking for something more efficient.

From your code, you certainly meant "symetric" and not diagonal. 

Maybe you can speed up things a bit by assigning slices:

>>> for k in range(m): 
...     z[k:, k] = z[k, k:]



-- 
Alexandre Fayolle                              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: signature.asc
Type: application/pgp-signature
Size: 481 bytes
Desc: Digital signature
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20080326/67905ff1/attachment.sig>


More information about the NumPy-Discussion mailing list