Is there a way to use the diag() function in a Matrix without using the built-in function or iteration?
diag()
M<-matrix(1:9, ncol=3) # make a m
You can use the functions row and col to find the indices where the column number is identical to the row number:
row
col
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