R – Get Element of Matrix at [Row, Column]
To get an element of a matrix present at given row and column, specify the row number and column number, separated by comma, in square brackets, after the matrix variable name. This expression returns the element in the matrix at specified row and column.
In this tutorial, we will learn how to access an element at given row and column.
The syntax to access element at given row and column in a matrix is
The expression returns the element in matrix
X at given
In the following program, we create a matrix and access the element at row 2, column 3.
data <- c(2, 4, 7, 5, 10, 8) A <- matrix(data, nrow = 2) element <- A[2, 3] print(element)
If the row number or column number is out of bounds for a given matrix, then R throws Error “subscript out of bounds”.
Let us try to access an element at
row = 8 and
column = 3, where the matrix is of size 2 x 3.
data <- c(2, 4, 7, 5, 10, 8) A <- matrix(data, nrow = 2) element <- A[8, 3] print(element)
Error in A[8, 3] : subscript out of bounds
In this R Tutorial, we learned how to get element of a Matrix at given row and column in R, with the help of examples.