Home > Back-end >  Make symmetric matrix from vector
Make symmetric matrix from vector

Time:10-13

I have to convert the vector into matrix

x<-c(1:5)
mat<-matrix(nrow=3, ncol=3)
for (i in 1:3){
  for (j in 1:3){
    if (i==j) {
      mat[i,j]<-x[3]
    } else 
      if (i < j) { ##for upper diagonal
        mat[i,j]<-x[j]
      }
  }
}

The resultning matrix shall be

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

I know that it is a kind of toeplitz matrix and there are packages available in R, but i have to do that with nested for loops.

CodePudding user response:

This may be done with toeplitz and the function is from base R i.e. no packages are needed

 `diag<-`(toeplitz(x)[-(2:3), 1:3], 1)
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    1    2
[3,]    5    4    1

Regarding the nested loop, an option is

x <- c(1:5)
mat <- matrix(nrow=3, ncol=3)
for (i in 1:3){
  for (j in 1:3){
    if (i==j) {
      mat[i,j]<-x[1]
    } else if (i > j) { 
         if((i   j) < length(x)){
            mat[i,j] <- x[(i   j   1)]
         } else {
            mat[i, j] <- x[(i   j) - 1]
         }  
      } else {
          if((i   j) < length(x)) {
           mat[i, j] <- x[j]
          } else {
            mat[i, j] <- x[i]
          }
              }
  }
}

-output

> mat
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    1    2
[3,]    5    4    1
  • Related