I have a matrix with diagonals equal to zero and off-diagonals all equal to one (the inverse of an 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 is always the same length as the dims of the matrix and always starts at 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 matrix of dims 9 by 9, for example, and a vector of 0:8 I can achieve the equivalent result. Any ideas for how to approach this?
As vec1 starts with a zero, then you can do :
So there’s no need to take the mat1 in the input, as that one is actually redundant. You can just construct the matrix within the function.
The trick is in providing a sequence of id values to select from the vector, and then transform everything to a matrix.
Edit : If you’re only going to use sequences, you could as well do :