# Given a position in a vector returns the position in a matrix RowColIndices
# or in a 3D-array ArrayIndices

# ---------------------------------------------------------
# example 1:
 wt <- array(unlist(lapply(1:60, function(x) {sample(1:4)})),
              c(member = 4, sdate = 20, ftime = 3))
 wt1 <- which(wt == 1)
 wt2 <- which(wt == 2)
 wt3 <- which(wt == 3)
 wt4 <- which(wt == 4)
#ArrayIndices(number = 36, dim1 = 4, dim2 = 20, dim3 = 3)
#ArrayIndices(number = 100, dim1 = 4, dim2 = 20, dim3 = 3)
# example 2:
 wt <- array(unlist(lapply(1:18, function(x) {sample(1:4)})),
              c(member = 4, sdate = 6, ftime = 3))    
 wt1 <- which(wt == 1)
 wt2 <- which(wt == 2)
 wt3 <- which(wt == 3)
#ArrayIndices(number = 36, dim1 = 4, dim2 = 6, dim3= 3)
# example 3:
 wt <- array(unlist(lapply(1:12, function(x) {sample(1:3)})), 
              c(member = 2, sdate = 6, ftime = 3)) 
 wt1 <- which(wt == 1)
 wt2 <- which(wt == 2)
 wt3 <- which(wt == 3)
#ArrayIndices(number = 36, dim1 = 2, dim2 = 6, dim3= 3)
# # I want the positions in each dimension
ArrayIndices <- function(number, dim1, dim2, dim3) {
  if (number <= dim1*dim2) {
    pos <- RowColIndices(number, dim1, dim2)
    pos1 <- pos[[1]]
    pos2 <- pos[[2]]
    pos3 <- 1
  } else {
     pos <-  RowColIndices(number, dim1, dim2)
     pos1 <- pos[[1]]
     pos <- RowColIndices(pos[[2]], dim2, dim3)
     pos2 <- pos[[1]]
     pos3 <- pos[[2]]
  }
  return(list(dim1 = as.numeric(pos1), 
              dim2 = as.numeric(pos2), 
              dim3 = as.numeric(pos3)))
}
# matrix 
RowColIndices <- function(number, num_row, num_col) {
     pos_col <- ceiling(number / num_row)
     pos_row <- (number - pos_col * num_row) + num_row
    return(list(row = pos_row, col = pos_col))
}

