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

Hoyt Koepke hoytak@gmail....
Wed Mar 26 12:25:39 CDT 2008

```If the rest of the matrix is already zeros and memory wasn't a
problem, you could just use

A_sym = A + A.T - diag(diag(A))

If memory was an issue, I'd suggest weave.inline (if that's a viable
option) or pyrex to do the loop, which would be about as fast as you
could get.

--Hoyt

On Wed, Mar 26, 2008 at 7:22 AM, Alexandre Fayolle
<alexandre.fayolle@logilab.fr> wrote:
> 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
>
> -----BEGIN PGP SIGNATURE-----
>  Version: GnuPG v1.4.6 (GNU/Linux)
>
>  iQEVAwUBR+pcDl6T+PKoJ87eAQI1zAf/W7wnB1a6sa4FuHDPTDjU61ZpvDgS41r7
>  B7EuSDncTluf3Y5ynQ8NroAihX0DvV4F5LTDcbFJbmqnQx8JApVoeQF3wnTnpf24
>  pUQ5oSB+w0+RtzU0Zu/TBkOh3hM8iPYyB2M7jq9/qakVxEsrlOiTH+j05ysJD9FG
>  GezArMoQu5ycJ26Ir9P7jR0acH/WBA84U524aiDbenLMmpFIZX7mElU47z/Ue5m7
>  xKTT/lu3BWQAJPoQTiHG7nRLDaAqxKVO0WLXPuUJ7HyCc4qjURhXZMmJQ2FP2ajt
>  H9AQQhNkO7eUAPmMLhK0x262bYIdq699UmjV7YOVmSvCrBM76okqew==
>  =ha+1
>  -----END PGP SIGNATURE-----
>
> _______________________________________________
>  Numpy-discussion mailing list
>  Numpy-discussion@scipy.org
>  http://projects.scipy.org/mailman/listinfo/numpy-discussion
>
>
```