1

我正在使用以下代码创建表示 [0,1]^d 的广告维度超立方体,该代码是由该论坛上的另一位用户提出的。

## generation of the d-dimensional hypercube
cube <- do.call(expand.grid,replicate(d, seq_len(mesh)/mesh, simplify=FALSE))

假设我有一个功能,比如说

 foo <- function(u) prod(u)

我想应用于上面创建的hybercube的每个点。有没有一种很好的方法可以避免在 d 行中使用循环来这样做?我尝试使用各种应用功能,但没有成功。

谢谢。

4

1 回答 1

0

First of all, a function for giving you the coordinates of the vertices:

hypercube <- function(d, coord = c(0, 1))
    do.call(expand.grid, replicate(d, coord, simplify = FALSE))

For example, using d = 3:

cube <- hypercube(d = 3)
cube
#   Var1 Var2 Var3
# 1    0    0    0
# 2    1    0    0
# 3    0    1    0
# 4    1    1    0
# 5    0    0    1
# 6    1    0    1
# 7    0    1    1
# 8    1    1    1

Then, to run your foo function on every vertex of the hypercube, use apply:

apply(cube, 1, foo)
于 2013-03-14T02:02:11.207 回答