To find the rank of a matrix in R, you can use the qr()
function followed by the qr.R()
function, and then count the number of non-zero rows in the resulting upper triangular matrix.
In this example,
matrix1
using the matrix()
function with a vector of values c(1, 2, 3, 4)
and specify the number of rows as 2.qr()
function on matrix1
to perform QR decomposition and store the result in a variable called qr1
.qr.R()
function on qr1
..Machine$double.eps
).matrix1 <- matrix(c(1, 2, 3, 4), nrow = 2)
qr1 <- qr(matrix1)
R1 <- qr.R(qr1)
rank1 <- sum(abs(diag(R1)) > .Machine$double.eps)
print(rank1)
[1] 2
In this example,
matrix2
using the matrix()
function with a vector of values c(1, 2, 3, 4, 5, 6, 7, 8, 9)
and specify the number of rows as 3.qr()
function on matrix2
to perform QR decomposition and store the result in a variable called qr2
.qr.R()
function on qr2
..Machine$double.eps
).matrix2 <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3)
qr2 <- qr(matrix2)
R2 <- qr.R(qr2)
rank2 <- sum(abs(diag(R2)) > .Machine$double.eps)
print(rank2)
[1] 2
In this example,
matrix3
using the diag()
function with a value of 3.qr()
function on matrix3
to perform QR decomposition and store the result in a variable called qr3
.qr.R()
function on qr3
..Machine$double.eps
).matrix3 <- diag(3)
qr3 <- qr(matrix3)
R3 <- qr.R(qr3)
rank3 <- sum(abs(diag(R3)) > .Machine$double.eps)
print(rank3)
[1] 3
In this tutorial, we learned How to find Rank of a Matrix in R language with well detailed examples.