Indexing a matrix

Changing ther diagomal

x<-matrix(0,5,5)
diag (x) <- 1:5
x
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    0    0    0    0
## [2,]    0    2    0    0    0
## [3,]    0    0    3    0    0
## [4,]    0    0    0    4    0
## [5,]    0    0    0    0    5

But this can also be done in another way.

x<-matrix(0,5,5)
y <- outer(1:5, 1:5, "==")
y
##       [,1]  [,2]  [,3]  [,4]  [,5]
## [1,]  TRUE FALSE FALSE FALSE FALSE
## [2,] FALSE  TRUE FALSE FALSE FALSE
## [3,] FALSE FALSE  TRUE FALSE FALSE
## [4,] FALSE FALSE FALSE  TRUE FALSE
## [5,] FALSE FALSE FALSE FALSE  TRUE
x[y] <- 1:5
x
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    0    0    0    0
## [2,]    0    2    0    0    0
## [3,]    0    0    3    0    0
## [4,]    0    0    0    4    0
## [5,]    0    0    0    0    5

Changing a triangular part

x<-matrix(0,5,5)
y <- outer(1:5,1:5,"<")
y
##       [,1]  [,2]  [,3]  [,4]  [,5]
## [1,] FALSE  TRUE  TRUE  TRUE  TRUE
## [2,] FALSE FALSE  TRUE  TRUE  TRUE
## [3,] FALSE FALSE FALSE  TRUE  TRUE
## [4,] FALSE FALSE FALSE FALSE  TRUE
## [5,] FALSE FALSE FALSE FALSE FALSE
x[y]<-1:10
x
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    0    1    2    4    7
## [2,]    0    0    3    5    8
## [3,]    0    0    0    6    9
## [4,]    0    0    0    0   10
## [5,]    0    0    0    0    0

Changing some of the minor diagonals

x <- matrix (0, 5, 5)
y <- outer(1:5,1:5,function(x,y) ((x + y) %% 2) == 0)
y
##       [,1]  [,2]  [,3]  [,4]  [,5]
## [1,]  TRUE FALSE  TRUE FALSE  TRUE
## [2,] FALSE  TRUE FALSE  TRUE FALSE
## [3,]  TRUE FALSE  TRUE FALSE  TRUE
## [4,] FALSE  TRUE FALSE  TRUE FALSE
## [5,]  TRUE FALSE  TRUE FALSE  TRUE
x [y] <- 1
x
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    0    1    0    1
## [2,]    0    1    0    1    0
## [3,]    1    0    1    0    1
## [4,]    0    1    0    1    0
## [5,]    1    0    1    0    1

Note that this can also be done, somewhat more clunkily, with

x <- matrix (c(1,0), 5, 5)
## Warning in matrix(c(1, 0), 5, 5): data length [2] is not a sub-multiple or
## multiple of the number of rows [5]
x
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    0    1    0    1
## [2,]    0    1    0    1    0
## [3,]    1    0    1    0    1
## [4,]    0    1    0    1    0
## [5,]    1    0    1    0    1

Using the subset() command

x <- matrix (0, 5, 5)
rownames(x) <- c ("aa", "ab", "ba", "bb", "cc")
colnames(x) <- c ("aa", "ab", "ba", "bb", "cc")
x
##    aa ab ba bb cc
## aa  0  0  0  0  0
## ab  0  0  0  0  0
## ba  0  0  0  0  0
## bb  0  0  0  0  0
## cc  0  0  0  0  0
subset (x, substr(rownames(x),1,1)=="a", (1 : 5) %% 2 == 0)
##    ab bb
## aa  0  0
## ab  0  0