Create an integer similarity matrix using R

I have a matrix with diagonals equal to zero and off-diagonals equal to unity (inverse to the identity matrix):

mat1 <- matrix(c(0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0), 5, 5)

I also have a vector that always has the same length as the dims of the matrix, and always starts from zero:

vec1 <- c(0,1,2,3,4)

using these two objects, I want to create a matrix that looks like this:

mat2 <- matrix(c(0,1,2,3,4,1,0,1,2,3,2,1,0,1,2,3,2,1,0,1,4,3,2,1,0), 5, 5)

     [,1] [,2] [,3] [,4] [,5]
[1,]    0    1    2    3    4
[2,]    1    0    1    2    3
[3,]    2    1    0    1    2
[4,]    3    2    1    0    1
[5,]    4    3    2    1    0

I want an operation that will generalize so that if I have a dims matrix of 9 by 9, for example, and a 0: 8 vector, I can achieve an equivalent result. Any ideas on how to approach this?

+5
source share
3 answers

Since vec1 starts from scratch, you can do:

MakeMatrix <- function(x){
  n <- length(x)
  id <- abs(rep(1:n,n)-rep(1:n,each=n)) + 1
  matrix(x[id],ncol=n)
}

MakeMatrix(vec1)

, mat1 , . .

id , .


: , :

MakeMatrix <- function(n){
  id <- abs(rep(1:n,n)-rep(1:n,each=n))
  matrix(id,ncol=n)
}

MakeMatrix(7)
+6

upper.tri lower.tri . , sequence.

n <- 9
vec <- (1:n)-1
m <- matrix(0, n, n)
m[lower.tri(m, diag=TRUE)] <- vec[sequence(n:1)]  #### Edit
m <- t(m)
m[lower.tri(m, diag=TRUE)] <- vec[sequence(n:1)]  #### Edit
m

      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
 [1,]    0    1    2    3    4    5    6    7    8
 [2,]    1    0    1    2    3    4    5    6    7
 [3,]    2    1    0    1    2    3    4    5    6
 [4,]    3    2    1    0    1    2    3    4    5
 [5,]    4    3    2    1    0    1    2    3    4
 [6,]    5    4    3    2    1    0    1    2    3
 [7,]    6    5    4    3    2    1    0    1    2
 [8,]    7    6    5    4    3    2    1    0    1
 [9,]    8    7    6    5    4    3    2    1    0
+6

:

genMat <- function(n){
  mat <- outer(1:n,1:n,"-")%%n
  tmp <- mat[lower.tri(mat)]
  mat <- t(mat)
  mat[lower.tri(mat)] <- tmp
  mat
}

> genMat(5)
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    1    2    3    4
[2,]    1    0    1    2    3
[3,]    2    1    0    1    2
[4,]    3    2    1    0    1
[5,]    4    3    2    1    0

Edit

vec1:

genMat2 <- function(vec){
  n <- length(vec)
  mat <- outer(1:n,1:n,"-")%%n
  tmp <- mat[lower.tri(mat)]
  mat <- t(mat)
  mat[lower.tri(mat)] <- tmp
  matrix(vec[mat+1],n,n)
}

> genMat2(c(0,2,4,3,9))
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    2    4    3    9
[2,]    2    0    2    4    3
[3,]    4    2    0    2    4
[4,]    3    4    2    0    2
[5,]    9    3    4    2    0

2 , , , abs , 1-:

abs(outer(1:n,1:n,"-"))

,

genMat <- function(n){
  abs(outer(1:n,1:n,"-"))
}

genMat2 <- function(vec){
  n <- length(vec)
  matrix(vec[abs(outer(1:n,1:n,"-"))+1],n,n)
}
+1

All Articles