[英]R- outer with matrix
Let's suppose I want to minimize a function: 假设我要最小化一个函数:
x<-seq(-4.5,4.5,by=.2)
y<-seq(-4.5,4.5,by=.2)
f <- function(x1,x2){(x1^2 + x2)^2 }
z <- outer(x,y,f)
Where z is a matrix of dimension 46 x 46: 其中z是尺寸为46 x 46的矩阵:
> class(z)
[1] "matrix"
> dim(z)
[1] 46 46
So I make a graph of the result with: 所以我用以下方法制作了一个结果图:
persp(x,y,z,phi=-45,theta=45,col="yellow",shade=.65 ,ticktype="detailed")
If I write the previous, it works, but since I want to minimize the function using optim, if I use that I get: 如果我编写了以前的版本,它可以工作,但是由于我想使用optim最小化该函数,因此如果得到,我将得到:
optim(c(-4,-4), f, df)$par
> Error in fn(par, ...) : argument "x2" is missing, with no default
So I need to use an array in order to use optim after all. 所以我毕竟需要使用数组才能使用优化。 So if I write: 所以如果我写:
f <- function(x) (x[1]^2 + x[2])^2
x <- seq(-4.5,4.5,by=.2)
y <- seq(-4.5,4.5,by=.2)
s<-data.frame(cbind(x,y))
I can use optim: 我可以使用优化:
optim(c(-4,-4), f, df)$par
But outer gives an error: 但是外部给出了一个错误:
z <- outer(s,f)
Error in as.vector(x, mode) : cannot coerce type 'closure' to vector of type 'any' as.vector(x,mode)中的错误:无法将类型“ closure”强制为“ any”类型的vector
I don't know how to solve it. 我不知道该怎么解决。
I believe the goal here is to not have to write the function two different ways, right? 我相信这里的目标是不必以两种不同的方式编写函数,对吗?
f0 <- function(x1,x2) ( x1^2 + x2 )^2
f <- function(x) ( x[1]^2 + x[2] )^2
Similarly, maybe you just want to use just s<-data.frame(cbind(x,y))
(without x
and y
). 同样,也许您只想使用s<-data.frame(cbind(x,y))
(没有x
和y
)。
Here's what I would consider doing: 这是我会考虑做的事情:
outer(s[[1]],s[[2]],Vectorize(function(xi,yi) f(c(xi,yi))))
This way you only have to write the function once, in the way amenable to using optim
(with a single argument). 这样,您只需要编写一次函数,就可以使用optim
(带有单个参数)。
Note: If you want the grids x
and y
to have a different number of points, you should store s <- list(x,y)
instead. 注意:如果希望网格x
和y
具有不同数量的点,则应存储s <- list(x,y)
。 The code will work the same. 该代码将相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.