R-给定一个矩阵和一个幂,产生包含矩阵列所有组合的多个矩阵 [英] R - Given a matrix and a power, produce multiple matrices containing all combinations of matrix columns
问题描述
给出一个矩阵mat
(大小为N
乘以M
)和一个幂p
(例如4),产生p
矩阵,其中每个p
矩阵包含所有可能的矩阵mat
中的列在该程度的组合.
Given a matrix mat
(of size N
by M
) and a power, p
(e.g., 4), produce p
matrices, where each p
-th matrix contains all possible combinations of the columns in mat
at that degree.
在我当前的方法中,我生成第p
个矩阵,然后在下一次调用中使用它来生成第p+1
个矩阵.对于给定的电源p
,这可以自动化"吗,而不是手动完成?
In my current approach, I generate the p
-th matrix and then use it in the next call to produce the p+1
th matrix. Can this be 'automated' for a given power p
, rather than done manually?
我是R的新手,并且了解实现此解决方案的方法可能比以下尝试更有效,更优雅...
I am a novice when it comes to R and understand that there is likely a more efficient and elegant way to achieve this solution than the following attempt...
N = 5
M = 3
p = 4
mat = matrix(1:(N*M),N,M)
mat_1 = mat
mat_2 = t(sapply(1:N, function(i) tcrossprod(mat_1[i, ], mat[i, ])))
mat_3 = t(sapply(1:N, function(i) tcrossprod(mat_2[i, ], mat[i, ])))
mat_4 = t(sapply(1:N, function(i) tcrossprod(mat_3[i, ], mat[i, ])))
任何人都可以提供一些建议吗?我的目标是为给定的矩阵mat
和功效p
创建一个函数,以更自动化"的方式输出p
不同的矩阵.
Can anyone provide some suggestions? My goal is to create a function for a given matrix mat
and power p
that outputs the p
different matrices in a more 'automated' fashion.
让我开始学习的相关问题:如何用所有组合将两个矩阵的列相乘
Related question that got me started: How to multiply columns of two matrix with all combinations
推荐答案
您可以执行以下操作
N = 5
M = 3
p = 4
mat = matrix(1:(N*M),N,M)
res_mat <- list()
res_mat[[1]] <- mat
for(i in 2:p) {
res_mat[[i]] <- t(sapply(1:N, function(j) tcrossprod(res_mat[[i-1]][j, ], res_mat[[1]][j, ])))
}
这篇关于R-给定一个矩阵和一个幂,产生包含矩阵列所有组合的多个矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!