Search code examples
rdata-structuresfor-loopmathematical-optimization

In R producing matrix of vectors and search for the optimum


An elementary question: I apologize for it. In R I would like to produce a data structure x with 2 indices, let us say i and j, s.t. (pseudocode)

for (i in 1:10){
  for (j in 1:20){
    x[i,j] <- c(i+j,j-i^2)
  }
}

i.e. each element of x is a vector with 2-components. Moreover, I would like to search in x to find which pair i,j gives the maximum value of j-i^2; this should be accomplished in the above double for. Could you please give me some hints? I thank you all.


Solution

  • You can accomplish this with outer. It is not clear from your question whether you are considering i and j as absolute values or as some sort of index vector. I am assuming that they are indices of a vector, x:

    set.seed(1) 
    x <- runif(20) 
    matm <- outer( x[1:20] , (x[1:10])^2 , `-` )
    matp <- outer( x[1:10] , x[1:20] , `+` )
    
    head( cbind( i_plus_j = c(matm) , j_minus_i_sq = c(matp) ) )
    #      i_plus_j j_minus_i_sq
    #[1,] 0.1950138    0.5310173
    #[2,] 0.3016290    0.6376326
    #[3,] 0.5023585    0.8383620
    #[4,] 0.8377129    1.1737165
    #[5,] 0.1311871    0.4671906
    #[6,] 0.8278948    1.1638983
    
    
    which( matm == max( matm ) , arr.ind = TRUE  )
    #     row col
    #[1,]  18  10