0

I have picewise cubic function and I want to find all the local maxima of it, how can I find all peaks?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
rose
  • 1,971
  • 7
  • 26
  • 32

2 Answers2

2

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
mrip
  • 14,913
  • 4
  • 40
  • 58
  • Thanks, but how can I find all local maxima if we have more than one local maximum ? – rose Oct 14 '13 at 00:23
  • :I got this result with your code:> optimize(f,c(0,5),maximum=T) $minimum [1] 4.999922 $objective [1] -46.54533 Warning message: In if (maximum) { : the condition has length > 1 and only the first element will be used. How did you get the maximum? – rose Oct 14 '13 at 00:33
  • To find more local maxima, briefly, the strategy would to find the first local maximum, then find the next local minimum after that, then the next local maximum, etc. – mrip Oct 14 '13 at 00:51
0

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))))
Max Candocia
  • 4,294
  • 35
  • 58
  • We have a function of z not x, how can I get the local maxima with your code? – rose Oct 14 '13 at 05:08
  • x is just whatever you want to plug in. It doesn't matter what variable you name the parameter it's passed to. All you need to do is assign x, define f(z) (or f(x), f(q), f(llama), etc.), and then run the code. It should handle every case for finite values. – Max Candocia Oct 14 '13 at 14:38