R中的函数最小化

时间:2017-10-28 05:35:44

标签: r

您好我在rm(list=ls()) library(deSolve) l <- 0.5 # bone 1/2 thickness (cm) x_vec <- c(0.05, 0.15, 0.25, 0.30, 0.45) A1meas <- c(0.51, 0.55, 0.64, 0.70, 0.92) # x_vec <- -x_vec*l l234 <- 2.8262e-6/(365.25*24*3600) length_series <- 100 funmin <- function(x) { A1_0 <- 0.025 # (238U) at the surface of the bone (disintegrations per second) K <- x[1] # D/R diffusion coefficient/volumetric equilibirum constant t <- x[2] # age in yr t <- t*(365.25*24*3600) series238 <- vector(mode="numeric", length=length_series+1) A1calc <- vector(mode="numeric", length=length(x_vec)) i <- 0 for (x in x_vec){ for (n in 0:length_series){ series238[n+1] <- (-1)^n/(2*n + 1)*exp(-K*((2*n + 1)^2)*pi^2*t/(4*l^2))*cos((2*n + 1)/2*pi*x/l) } sum_series238 <- sum(series238) i <- i+1 A1calc[i] <- A1_0*(1 - 4/pi*sum_series238) } fmin <- (A1calc - A1meas)^2 } optim(c(1e-13, 1e4), funmin, method = "L-BFGS-B", lower = c(1e-16, 1e3), upper = c(1e-8, 1e6)) 函数中尝试最小化wreq,但我收到此错误消息:

  

optim中的错误(c(1e-13,10000),funmin,method =&#34; L-BFGS-B&#34;,lower =   c(1e-16,:optim中的目标函数评估长度为5而不是1

任何想法我做错了什么?见下面的代码。

0.5

1 个答案:

答案 0 :(得分:0)

得到它......正如错误信息所说(呃!),评估的函数的长度为5而不是这个。 这有效:fmin <- sum((A1calc - A1meas)^2)