【发布时间】:2018-06-12 12:10:30
【问题描述】:
我有四个使用此函数转换为矩阵的大型列表:
array(as.matrix(unlist(mat2)), dim=c(3, 80, 100))
我已取消列出将其转换为矩阵形式的列表(不确定是否需要,但 object.size 作为矩阵要小得多)。如果使用列表更容易,请说出来。矩阵/列表有 132 个元素,但为了简单起见,我们在这里假设为 100。
mat1
num [1:80, 1:100] 0.00669 0.00603 0.00895 0.00771 0.01533 ...
mat2
num [1:80, 1:80, 1:100] 0.0033 -0.00474 -0.00261 0.00587 -0.00599 ...
mat3
num [1:3, 1:80, 1:100] 0.0159 -0.0131 -0.0131 -0.0656 0.0554 ...
mat4
num [1:10, 1:3] 0.00545 0.01043 0.00563 0.00431 0.00464 ...
这是我的功能:
customfunction <- function
(
mat1, # num [1:80, 1:100]
mat2, # num [1:80, 1:80, 1:100]
mat3=NULL, # num [1:3, 1:80, 1:100]
mat4=NULL, # num [1:10, 1:3]
a=0.025 # scalar
)
{
omega = diag(c(1,diag(a * mat3 %*% mat2 %*% t(mat3))))[-1,-1]
temp = solve(t(mat3) %*% solve(omega) %*% mat3 + solve(a * mat2))
out = temp %*% (solve(a * mat2) %*% mat1 + t(mat3) %*% solve(omega) %*% mat4)
return(out)
}
而不是运行:
customfunction(mat1[1,], mat2[,,1], mat3[,,1], mat4[1,])
customfunction(mat1[2,], mat2[,,2], mat3[,,2], mat4[1,])
customfunction(mat1[3,], mat2[,,3], mat3[,,3], mat4[1,])
...
customfunction(mat1[61,], mat2[,,61], mat3[,,61], mat4[2,])
customfunction(mat1[61,], mat2[,,61], mat3[,,61], mat4[2,])
etc...
或
customfunction(mat1[1,], mat2[[1]], mat3[[1]], mat4[1,])
customfunction(mat1[2,], mat2[[2]], mat3[[2]], mat4[1,])
customfunction(mat1[3,], mat2[[3]], mat3[[3]], mat4[1,])
...
customfunction(mat1[61,], mat2[[61]], mat3[[61]], mat4[2,])
customfunction(mat1[61,], mat2[[61]], mat3[[61]], mat4[2,])
请注意,mat4[i,] 在第 60 次迭代中更改,即我应用它 60 次,保持mat4[1,] 不变,然后在接下来的第 60 次迭代中应用 mat[2,]。是否可以应用(或循环)它,以便它为每个元素/行运行该函数 100 次,从而创建一个 100x80 矩阵?如果有,怎么做?
非常感谢!
【问题讨论】:
-
您能简化一下您的问题吗?并使用
dput函数提供mat1,2,3,4? -
@jogo 这适用于我的示例示例。我只是想尝试一下我的真实数据,希望它有效。
-
@jogo 它运行良好,但它有一个我忘记添加的限制。我现在已经编辑了我的主要帖子。是否有可能在每 60 次迭代或“应用程序”中保持
mat4不变? -
更改为
mat4[1+ (i-1)%/%60,] -
@jogo 谢谢!你是一个救生员 :-) 它完全奏效了。
标签: r loops matrix apply custom-function