findoptima | R Documentation |
This function finds the peaks and valleys on the curve of user-defined functions with one variable. The function also plots the function curve that can be used to demonstrate the points for local optima and global optimum in a optimization problem.
findoptima(x, type="max", pflag=TRUE)
x |
a vector of variable |
type |
Either “max” (the default) or “min”. The peaks are
found when |
pflag |
if this is TRUE, the first and last values are also checked. |
The findoptima function finds all the peaks and valleys in a given function curve. The points can be colorized with different colors. See the example below.
Returns a vector of indices of the peaks or valleys on the function curve.
Zeynel Cebeci & Erkut Tekeli
Cebeci Z. (2021). R ile Genetik Algoritmalar ve Optimizasyon Uygulamalari. Ankara:Nobel Akademik Yayincilik
fx <- function(x) -sin(x)-sin(2*x)-cos(3*x) + 3 x <- seq(-2*pi, 2*pi, by=0.001) curve(fx, x) cr <- curve(fx, x, lwd=2) xy <- cbind(cr$x, cr$y) peaks <- findoptima(cr$y, type = "max") valleys <- findoptima(cr$y, type = "min") ## Finds peaks and valleys peaks <- findoptima(cr$y, type="max") valleys <- findoptima(cr$y, type="min") ## Plotting the function curve and local optima and global optimum points(xy[peaks,], pch=19, cex=1.2, col=2) points(xy[valleys,], pch=18, cex=1.2, col=4) gmin <- valleys[which.min(xy[valleys,2])] gmax <- peaks[which.min(xy[valleys,2])] points(xy[gmax,1], xy[gmax,2], pch=19, cex=2, col=2) points(xy[gmin,1], xy[gmin,2], pch=18, cex=2, col=4) text(xy[gmax,1], xy[gmax,2], labels="Glob.Max", pos=2, cex=0.8, col=1) text(xy[gmin,1], xy[gmin,2], labels="Glob.Min", pos=2, cex=0.8, col=1)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.