R 如何使用值向量(如0:9)获得2×2矩阵的所有可能排列?
我在一份作业中遇到了一个问题。我被要求用0:9的值找出2×2矩阵所有可能排列的行列式。然而,我似乎无法找到所有可能的矩阵。我尝试过使用combn函数,但这只会给我提供具有唯一元素的矩阵(换句话说,它不会返回具有重复元素(如1,1,0,2)的矩阵)。谁能给我指一下正确的方向吗 我试过类似的方法R 如何使用值向量(如0:9)获得2×2矩阵的所有可能排列?,r,matrix,permutation,R,Matrix,Permutation,我在一份作业中遇到了一个问题。我被要求用0:9的值找出2×2矩阵所有可能排列的行列式。然而,我似乎无法找到所有可能的矩阵。我尝试过使用combn函数,但这只会给我提供具有唯一元素的矩阵(换句话说,它不会返回具有重复元素(如1,1,0,2)的矩阵)。谁能给我指一下正确的方向吗 我试过类似的方法 x <- 0:9 combn(x, 4) x以下是我的方法: # the input vector x <- c(0:9) # all 2x2 matrices pos <- expa
x <- 0:9
combn(x, 4)
x以下是我的方法:
# the input vector
x <- c(0:9)
# all 2x2 matrices
pos <- expand.grid(x,x,x,x)
# all dets:
dets <- pos$Var1*pos$Var3 - pos$Var2 * pos$Var4
# unique dets
unique(dets)
您可以尝试以下操作:
my_determinant_function <- function(x){
det(matrix(x, nrow = 2, ncol = 2))
}
df <- expand.grid(rep(list(0:9), 4))
apply(df,1, my_determinant_function)
my_determinate_functionRcppAlgos
是解决这类问题的绝佳工具
library(RcppAlgos)
x<- 0:9
unlist(
permuteGeneral(x, 4, repetition = T, FUN = function(y) det(matrix(y,2)))
)
# or for better performance
mat <- permuteGeneral(x, 4, repetition = T)
mat[,1] * mat[, 3] - mat[, 2] * mat[, 4]
library(RcppAlgos)
x<- 0:9
unlist(
permuteGeneral(x, 4, repetition = T, FUN = function(y) det(matrix(y,2)))
)
# or for better performance
mat <- permuteGeneral(x, 4, repetition = T)
mat[,1] * mat[, 3] - mat[, 2] * mat[, 4]
array(t(permuteGeneral(x, 4, repetition = T)), c(2,2,2500))