MathGroup Archive 2004

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Creating a symmetric matrix

  • To: mathgroup at
  • Subject: [mg46856] Re: [mg46853] Creating a symmetric matrix
  • From: Oleksandr Pavlyk <pavlyk at>
  • Date: Fri, 12 Mar 2004 02:02:41 -0500 (EST)
  • Organization: Penn State University; Department of Physics
  • References: <>
  • Reply-to: pavlyk at
  • Sender: owner-wri-mathgroup at

Hi Mark,

I this this one should be pretty efficient

Symmetrize[mat_] := mat + Transpose[mat] - 
DiagonalMatrix[Flatten[MapIndexed[#1[[#2]] & , mat]]];

given upper(or lower) triangular matrix mat at the input,
it adds its transposed and subtracts the diagonal.

I ran some tests, the time it takes is quadratic in
the size of mat, yet the time is considerable smaller
that it took to create random upper-triangular matrix.

Here is the code used

getUpperTriangular[dim_] := Table[If[n > m, 0,
   Random[Integer, {1,100}] ], {n, 1, dim}, {m, 1, dim}];

SetAttributes[getTiming, {HoldAll, SequenceHold}]
getTiming[expr_] := Timing[expr][[1]] /. {Second -> 1}

symt = {}; creat = {};
Do[creat = Append[creat, {dim, getTiming[mat = getUpperTriangular[dim]]}];
    symt = Append[symt, {dim, getTiming[res = Symmetrize[mat]]}]; , 
{dim, 10, 2000, 100}]

ListPlot[symt]  (* Graph of time it takes to symmetrize *)

ListPlot[symt]  (* Graph of time it takes to create the u-t. matrix *)

It takes 3.4 seconds to symmetrize a random matrix of 3000 x 3000
integers on my P4 2.0GHz w/ 768MB. And it took almost 18 seconds to
create such a matrix.


Mark Coleman wrote:

> Greetings,
> How can I efficiently build a symmetric matrix from an upper triangular 
> one, i.e., extract the upper triangular elements and insert them into 
> the lower triangle in such a way as to make the resulting square matrix 
> symmetric?
> Thanks,
> Mark

Office: 6H Osmond                    Web:
     No trees were destroyed to send this mail,
           but a lot of electrons were terribly disturbed.

  • Prev by Date: RE: Font size
  • Next by Date: Excessive Mathematica memory use, revisited.
  • Previous by thread: Re: Re: Re: Creating a symmetric matrix
  • Next by thread: Re: Creating a symmetric matrix