Search code examples
rmaximization

Finding the local maximum of piecewise cubic function in R


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


Solution

  • 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