【发布时间】:2020-03-27 01:09:06
【问题描述】:
我正在编写一个函数来解决数独难题。此函数的一部分将用于将矩阵拆分为三个 9x3 矩阵。然后,在将矩阵重新加入一个大矩阵之前,我将对每个矩阵执行操作。
对于这个阶段,我希望我的这部分功能做三件事:
- 将矩阵拆分为三个矩阵
- 为每个创建的矩阵命名
- 在同一函数中调用新矩阵
但是,我在第 3 步中苦苦挣扎。我编写了一个函数,将矩阵分成三个,命名每个新矩阵,如果我输入envir = globalenv() 行,该函数确实返回我的矩阵分成三个, 9x3 矩阵,每个矩阵都有其单独的标识符名称。太好了!
但是,我希望在函数的下一部分中调用函数的第 1 步和第 2 步创建的新矩阵。在运行函数之前我不会知道矩阵的名称,因为我希望代码可用于许多矩阵,无论大小如何。
有没有办法在 main 函数中调用由 assign 函数创建的对象,而我只知道对象的名称将是“mat_n”,其中 n 是一个整数。
为清楚起见,这是我的代码的简化版本:
m <- matrix(sample(c(0:9), 81, replace = T), ncol = 9, nrow = 9)
matrix_split <- function(x){
i <- 1:length(x[, 1])
a <- 1:sum(i %% 3 == 0) # Will be used to name the temporary matrices
b <- which(i %% 3 == 0) # Will be used to identify where to split main matrix
for(n in a){ # This is to create a number of smaller matrices depending on the
# number multiples of 3 that are present in the length of the object.
nam <- paste("mat_", n, sep = "") # Each new matrix will be named and numbered
# using the assign function below:
assign(nam, x[, c((b[a[n]] - (sum(i %% 3 == 0) - 1)) : b[a[n]])])
# Not a very elegant way of using the loop to split the matrix into blocks of
# three. b[a[n]] returns either 3, 6 or 9, and (sum(i %% == 3) -1 ) = 2. So this
# will return x[, c(1:3)], x[, c(4:6)] and x[, c(7:9)], when spliting the matrix
# into three.
}
}
matrix_split(m)
我只要求调用由 assign 函数创建的对象的特定解决方案,以便在创建后在我的 main 函数中使用。这将是一项有用的技能,并且是我编程知识的空白(根本不是很广泛)。
这可能也不是拆分矩阵的最佳方法,而且我知道已经创建了一些包可以解决数独难题,但我想自己编写,没有比做事更好的学习方法了一开始很糟糕,然后改进它。
【问题讨论】:
标签: r function assign calling-convention