MathGroup Archive 2004

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

Search the Archive

Re: Creating a symmetric matrix

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

Hi Mark,

I this this one should be pretty efficient

In[1]:=
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

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

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

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

In[5]:=
ListPlot[symt]  (* Graph of time it takes to symmetrize *)

In[6]:=
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.

Best,
Sasha

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: http://www.pavlyk.com
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     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