The diag() function in R
r
Solution
You can use the functions `row` and `col` to find the indices where the column number is identical to the row number:
row(M) == col(M)
# [,1] [,2] [,3]
# [1,] TRUE FALSE FALSE
# [2,] FALSE TRUE FALSE
# [3,] FALSE FALSE TRUE
M[row(M) == col(M)]
# [1] 1 5 9
Problem
Is there a way to use the `diag()` function in a Matrix without using the built-in function or iteration? ``` M<-matrix(1:9, ncol=3) # make a matrix q5b<-function(M){ #function } ``` I know that `M[1,1]`, `M[2,2]`, and `M[3,3]` will give me the same output as `diag(M)`. However, I can't think of a way to do this without a for loop. My thought process was I should have a condition where `row index == column index` in the Matrix then print that value. I appreciate any suggestions.