简体   繁体   中英

Finding the local maximum of piecewise cubic function in R

我有picewise立方体函数,我想找到它的所有局部最大值,我怎样才能找到所有峰值?

One option is to find the maximum numerically using optimize . First you have to write the actual function:

x <- c(0.014, 0.034, 0.059, 0.061, 0.069, 0.080, 0.123, 0.142, 0.165, 
   0.210, 0.381, 0.464, 0.479, 0.556, 0.574, 0.839, 0.917, 1.649, 1.702, 
   1.893, 1.932 ,2.337, 2.628, 4.510, 4.584, 5.267, 5.299)
f<-function(z){
    z1<-pmax(0,z-x)
    sum(z1^2-(z^3-z1^3)/3)
}

Then:

> optimize(f,c(0,5),maximum=T)
$maximum
[1] 2.22133

$objective
[1] 8.486057

I came up with a way to do this with regular expressions, and there are probably better ways to find all local maxima of a cubic function, but this works pretty well. It will also take into account repeated values and boundary conditions.

vals=f(x)

text=paste0(substr(format(diff(vals),scientific=TRUE),1,1),collapse="")
sort(na.omit(c(gregexpr('[ ][0]*-',text)[[1]]+1,ifelse(grepl('^-',text),1,NA),
 ifelse(grepl('[^-]$',text),length(vals),NA))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM