R contour3d 为一个函数给出 "subscript out of bounds" 而不是另一个 returns 相同的值

R contour3d gives "subscript out of bounds" for one function but not another that returns identical values

使用 here 中的示例...

#this works fine
f <- function(x, y, z) x^2+y^2+z^2

#but I want to try it with vectors it fails
vec_dot <- function(a, b) sum(a*t(b))
f <- function(x, y, z) vec_dot(c(x,y,z), c(x,y,z))

#check some values each function returns
for(y in 1:10) {print(f(y/10,0,0))}

#draw the isosurface
d <- seq(-2, 2, len=20)
contour3d(f,Tc,d,d,d,engine="standard")

当我 运行 我得到:

Error in tris[3 * (1:n) - 2, ] : subscript out of bounds
Calls: contour3d ... contourTriangles -> makeTriangles -> unzipTriangleMatrix

但是注释掉第二个 f 有效,给了我一个球体。据我所知,这两个函数 f 给出的值完全相同。是否有一些隐藏的 number-type-that-fails-with-contour3d sum() returns 但 print() 与常规数字完全相同?

您的函数 vec_dotf 不能很好地向量化。 contour3d函数传入一个xyz值的向量,只调用一次f函数。

所以与其调用

for(y in 1:10) {print( f(y/10,0,0) )}

R 通常一次传递它想要的所有值

print( f(1:10/10,0,0) )

如您所见,只有 returns 一个值。您可以使用 Vectorize 辅助函数来 "fix" 您的函数

f <- Vectorize(function(x, y, z) vec_dot(c(x,y,z), c(x,y,z)))

但原来的定义

f <- function(x, y, z) x^2+y^2+z^2

它的效率可能要高得多。