我希望減少時間和內存使用(I以前使用外此,但它消耗更多的內存比我)通過減少迭代以創建一個對稱矩陣,即sol[i, j]
相同sol[j, i]
。For循環創建對稱矩陣
到目前爲止我的代碼:
# Prepare input
subss <- list(a = c(1, 2, 4), b = c(1, 2, 3), c = c(4, 5))
A <- matrix(runif(25), ncol = 5, nrow = 5)
# Pre allocate memory
sol <- matrix(nrow = length(subss), ncol = length(subss),
dimnames = list(names(subss), names(subss)))
x <- 0
for (i in seq_along(subss)) {
# Omit for the subsets I already calculated ?
for (j in seq_along(subss)) {
x <- x + 1
message(x)
# The function I use here might result in a NA
sol[i, j] <- mean(A[subss[[i]], subss[[j]]])
sol[j, i] <- sol[i, j] # Will overwrite when it shouldn't
}
}
將使用9次迭代,如何避免他們做到這6次迭代?
我需要計算對稱值,因此this question不適用。此other one也不工作,因爲可能有很多組合,並且在某些時候它不能在內存中分配矢量。
不行,首先它不會用我的subss,所以你提出什麼尺寸爲5×5不3x3的,第二我真正的函數,而不是意味着更復雜的 – Llopis