s-news
[Top] [All Lists]

Re: creating a square matrix from a vector

To: "Walter R. Paczkowski" <dataanalytics@earthlink.net>
Subject: Re: creating a square matrix from a vector
From: David L Lorenz <lorenz@usgs.gov>
Date: Tue, 15 Aug 2006 07:43:21 -0500
Cc: s-news@lists.biostat.wustl.edu
Importance: Normal
Walt,
  The lower.tri() function references the lower triangle of a square matrix. To generate your example matrix:
mat <- matrix(0, nrow=4, ncol=4)
mat[lower.tri(mat)] <- 1:6
mat <- mat + t(mat)
 
  If you have a general problem, then you can use the quadratic equation to determine the number of rows and columns from the length of the vector. For a vector of length 325, the matrix must be 26 by 26.
Dave
-----s-news-owner@lists.biostat.wustl.edu wrote: -----

To: s-news@lists.biostat.wustl.edu
From: "Walter R. Paczkowski" <dataanalytics@earthlink.net>
Sent by: s-news-owner@lists.biostat.wustl.edu
Date: 08/15/2006 06:24AM
Subject: [S] creating a square matrix from a vector

Good morning,

I have a vector of, say, 6 numbers (1:6) that represents the upper triangle of a square matrix that has 0 on the main diagonal.  I want to create that matrix.  So, if my vector is 1:6, I want

0  1  2  3
1  0  4  5
2  4  0  6
3  5  6  0

How can I do this easily?  Any suggestions?  The actual vector for my project has 325 elements so typing it in is not an option.

Thanks for any help.

Walt Paczkowski

_________________________________

Walter R. Paczkowski, Ph.D.
Data Analytics Corp.
44 Hamilton Lane
Plainsboro, NJ  08536
(V) 609-936-8999
(F) 609-936-3733


<Prev in Thread] Current Thread [Next in Thread>