let's suppose have function f(x,y) , 2 vectors x , y, , want 2 find combination of values x , y gives maximum value of f .
*the function defined , bounded. x , y have approximately 1000 elements each.
*the function continuous, need highest point vector x , y though maximum might somewhere in between.
one possible implementation use 2 nested loops such in example; each x , y 10-element vectors , z=f(x,y)=x+y
max =-1 (x in 1:10){ (y in 2:20){ z = x+y if (z>max){ z=max x_sol = x y_sol = y } } } x_sol #10 y_sol #20
this code shows maximum value possible combinations of x , y when (x,y)=(10,20). code fine; problem when x , y hold more values, z more complex, , procedure has run hundreds of times, it's slow. wondering if there more elegant method replaces nested loop.
if want use brute-force approach optimization, vectorization fastest way achieve trying do:
x <- 1:100 y <- 1:100 df <- expand.grid(x=x,y=y) df$z <- df$x + df$y max(df$z)
this solution of course depends on kind of function want use.
Comments
Post a Comment