を使用する代わりにtryCatch
、関数を使用して行列式を単純に計算できますdet
。行列式がゼロの場合に限り、行列は特異です。
したがって、行列式がゼロと異なるかどうかをテストし、テストが正の場合にのみ逆行列を計算できます。
set.seed(1)
count <- 1
inverses <- vector(mode = "list", 100)
repeat {
x <- matrix(sample(0:2, 4, replace = T), 2, 2)
# if (det(x)) inverses[[count]] <- solve(x)
# a more robust replacement for the above line (see comment):
if (is.finite(determinant(x)$modulus)) inverses[[count]] <- solve(x)
count <- count + 1
if (count > 100) break
}
更新:
ただし、特異行列の生成を回避することは可能です。2行2列の行列式mat
は次のように決定されmat[1] * mat[4] - mat[3] * mat[2]
ます。この知識を使用して、乱数をサンプリングできます。特異行列を生成する数をサンプリングしないでください。もちろん、これは以前にサンプリングされた数値によって異なります。
set.seed(1)
count <- 1
inverses <- vector(mode = "list", 100)
set <- 0:2 # the set of numbers to sample from
repeat {
# sample the first value
x <- sample(set, 1)
# if the first value is zero, the second and third one are not allowed to be zero.
new_set <- ifelse(x == 0, setdiff(set, 0), set)
# sample the second and third value
x <- c(x, sample(new_set, 2, replace = T))
# calculate which 4th number would result in a singular matrix
not_allowed <- abs(-x[3] * x[2] / x[1])
# remove this number from the set
new_set <- setdiff(0:2, not_allowed)
# sample the fourth value and build the matrix
x <- matrix(c(x, sample(new_set, 1)), 2, 2)
inverses[[count]] <- solve(x)
count <- count + 1
if (count > 100) break
}
この手順は、生成されたすべての行列が逆行列になることを保証します。