Reputation: 1274
Suppose that we have the following code :
x1<- runif(40, min = -4.5, max = 4.5) # Create x vector
y1 <- runif(40, min = -4.5, max = 4.5) # Create y vector
custom_fun <- function(x, y) { # Create custom function in R ; here i used the beale function
z <- (1.5 - x + x*y)^2+(2.25 - x + x*y^2)^2+(2.625 - x + x*y^3)^2
return(z)
}
m <- outer(x1, y1, custom_fun)
print(m)
My question is how the obtain the list of the n minimum values of the matrix m , i need also to retrieve the correspending positions in the vectors x1 and y1 ( which means the couples from x1 and y1 that allow us to obtain those minimum values of the matrix m ).
For example , if the excecution of the previous code gives :
#m
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 508.64893 11.245614 7887.387 3.4916340 1.517622 3232.9724
[2,] 727.76775 19.629751 17649.225 46.0714031 63.427516 6708.3153
[3,] 2227.94868 7.948157 39784.638 0.3509784 6.073413 15901.8932
[4,] 56.06329 13.568900 432.400 11.4225081 10.455426 205.5854
[5,] 1723.86138 22.552465 39256.366 67.8455312 99.733390 15069.6231
[6,] 1328.44959 21.510099 30755.388 59.7772840 86.142180 11775.4025
and i'm wanting for example the p minimum values of the matrix , let p=3 then i will retrieve the values :
0.3509784 -1.517622- 3.4916340 ( those values are near the optimum of the beale function ).
Next , i need a way to retrieve the couples (x,y) that allow us to obtain those minimum values ( from the current excecution ! ) :
custom_fun(a1,b1)=0.3509784
custom_fun(a2,b2)=1.517622
custom_fun(a3,b3)=3.4916340
so how could i retrieve (a1,b1) from the current x1 and y1 vectors ??? I will need also to retrieve the couples (a2,b2) and (a3,b3). .
Another example , suppose the current excecution gives the following :
[1] "x4 list :"
[1] 2.0695110 3.7844526 -0.6914949
[1] "y4 list :"
[1] -4.079663 1.771313 -4.206778
[1] "matrix of objective function : denoted m "
[,1] [,2] [,3]
[1,] 20870.387 199.495204 25007.158
[2,] 70719.411 521.366216 84647.031
[3,] 2625.535 1.807467 3115.075
with p=2 ; the values 1.807467 and 521.366216 are good while searching the minimum, but the question is how to get their respective coordinates (x,y) from (x4,y4 ) possibilities.
I wish my question is clear.
Thank you a lot for help !
Upvotes: 0
Views: 36
Reputation: 388962
I guess something like this might help :
p <- 3
#Get p minimum value
p_minimum_value <- sort(m)[1:p]
#Get their row and column position
which(relist(m %in% p_minimum_value, m), arr.ind = TRUE)
Upvotes: 1