To get the size of a matrix in R, you can use the dim()
function. This function returns a vector containing the number of rows and columns of the matrix. Additionally, you can use the nrow()
and ncol()
functions to get the number of rows and columns separately.
In this example,
matrix
with values from 1 to 9 arranged in 3 rows and 3 columns using the matrix()
function.matrix()
function takes a vector of values and the arguments nrow
and ncol
to specify the number of rows and columns respectively.dim()
function to get the dimensions of the matrix. The dim()
function returns a vector where the first element is the number of rows and the second element is the number of columns.dimensions
and print it to standard output.matrix <- matrix(1:9, nrow = 3, ncol = 3)
dimensions <- dim(matrix)
print(dimensions)
[1] 3 3
In this example,
matrix
with values from 1 to 12 arranged in 3 rows and 4 columns using the matrix()
function.matrix()
function takes a vector of values and the arguments nrow
and ncol
to specify the number of rows and columns respectively.nrow()
function to get the number of rows in the matrix. The nrow()
function returns a single integer value representing the number of rows.num_rows
and print it to standard output.matrix <- matrix(1:12, nrow = 3, ncol = 4)
num_rows <- nrow(matrix)
print(num_rows)
[1] 3
In this example,
matrix
with values from 1 to 16 arranged in 4 rows and 4 columns using the matrix()
function.matrix()
function takes a vector of values and the arguments nrow
and ncol
to specify the number of rows and columns respectively.ncol()
function to get the number of columns in the matrix. The ncol()
function returns a single integer value representing the number of columns.num_columns
and print it to standard output.matrix <- matrix(1:16, nrow = 4, ncol = 4)
num_columns <- ncol(matrix)
print(num_columns)
[1] 4
In this tutorial, we learned How to get Matrix Size in R language with well detailed examples.