rmatrixsubmatrix

Extract submatrix from matrix


I create a matrix in R with 10x10 (10 rows and 10 columns): matriz <- matrix(1:100, nrow = 10, ncol = 10, byrow=T) I want to extract square submatrices (3x3) from matrix (matriz), randomly and without overlap.

I see a package in R named "subset.matrix", but I couldn't in randomly matrix.

Any suggestion?


Solution

  • I agree with the comment from user2974951 regarding randomness. However, this code block will do what you asked.

    matriz <- matrix(1:100, nrow = 10, ncol = 10, byrow=T)
    
    attempts <- 50
    
    # Initialize a list to hold the results
    sub_mats <- vector(mode = "list", length = attempts)
    
    # The top left corner of the matrix can't have an index > 8
    rand_x <- sample(1:8, attempts, replace = T)
    rand_y <- sample(1:8, attempts, replace = T)
    
    for (i in 1:attempts) {
      # Get the three-length vectors
      x_range <- rand_x[i] : (rand_x[i] + 2)
      y_range <- rand_y[i] : (rand_y[i] + 2)
      # Subset the matrix
      sub_mat <- matriz[x_range, y_range]
      # We'll use NAs to mark submatrices from previous loops
      if (any(is.na(sub_mat))) next
      # If there's no overlap, add it to the list
      sub_mats[[i]] <- sub_mat
      # Set this submatrix as NAs
      matriz[x_range, y_range] <- rep(NA, 9)
    }
    
    # Remove failed attempts
    sub_mats <- sub_mats[!sapply(sub_mats, is.null)]
    

    Instead of a set number of attempts for the loop, you could use a counter. With 50 attempts, I get 4-6 sub-matrices. 1000 gives 6-8.