Consider a matrix with r rows and c columns and containing v integers between 0 and v-1; in the following example, r=4, c=2, and v=6.
L <- c(0,1,1,2,0,1,2,3)
(x <- matrix(L,nrow=4,ncol=2,byrow = TRUE))
## 0 1
## 1 2
## 0 1
## 2 3
The goal is to generate a r*c (row) by v column incidence matrix, as follows:
- each row corresponds to one element of the original matrix (in column-major order, i.e. in the example here the 4th row corresponds to
x[4,1]and the 5th row corresponds tox[1,2]) - find the “neighbors” above and below each element, wrapping around (cyclically) from the top to the bottom of the matrix; count the number of neighbor elements for each value of
v.
For example, the first element in the matrix (x[1,1]) has neighbours 1 (below) and 2 (“above”, i.e. wrapped around to the bottom of the column; thus we enter 1 in columns 2 and 3 of row 1, matching the corresponding elements of 0:(v-1). The rest of the row is set to zero:
rownames 0 1 2 3 4 5
[1] 0 1 1 0 0 0
The next element (x[2,1]) has 0 on both sides (above and below), so the first column (corresponding to 0) is set to 2, with the rest of the elements equal to zero.
[2] 2 0 0 0 0 0
The full matrix for the example above is:
rownames 0 1 2 3 4 5
[1] 0 1 1 0 0 0
[2] 2 0 0 0 0 0
[3] 0 1 1 0 0 0
[4] 2 0 0 0 0 0
[5] 0 0 1 1 0 0
[6] 0 2 0 0 0 0
[7] 0 0 1 1 0 0
[8] 0 2 0 0 0 0
The row sums are each 2.
There might be a cleaner way to do this: