Skip to content

creating a symmetric matrix

4 messages · Erin Hodgess, William Dunlap, David L Carlson +1 more

#
Dear R People:

Suppose I have the following:

x <- 1:4

And I want to create the following matrix:

1 2 3 4
2 1 2 3
3 2 1 2
4 3 2 1

Is there a function in place for this, please?  I looked at  symMatrix
in micEcon and some of the items in Matrix, but they didn't quite do
it.

I can put together something quickly, of course, but it seems likely
that this would exist.

Thanks,
Erin
#
[,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    2    1    2    3
[3,]    3    2    1    2
[4,]    4    3    2    1

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
#
You asked for existing functions, but I was more intrigued by trying to
create one:

symmat <- function(n) {
     x <- matrix(1:n, nrow=n, ncol=n)
     abs(x-col(x))+1
}
[,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    2    1    2    3
[3,]    3    2    1    2
[4,]    4    3    2    1

----------------------------------------------
David L Carlson
Associate Professor of Anthropology
Texas A&M University
College Station, TX 77843-4352
#
???
A previous answer pointed out ?toeplitz

entering
gives

{
    if (!is.vector(x))
        stop("'x' is not a vector")
    n <- length(x)
    A <- matrix(0, n, n)
    matrix(x[abs(col(A) - row(A)) + 1], n, n)
}

Why reinvent?

-- Bert
On Fri, Sep 7, 2012 at 8:19 AM, David L Carlson <dcarlson at tamu.edu> wrote: