my.slice <- function(v,dm,d,j){
tmp <- list()
for(i in 1:length(dm)){
tmp[[i]] <- 1:dm[i]
}
tmp2 <- as.matrix(expand.grid(tmp))
return(list(v=v[which(tmp2[,d]==j)],dm=dm[-d]))
}
my.slice.2 <- function(v,dm,d,j){
j <- j-1
n <- length(dm)
dm. <- c(1,dm)
n <- length(dm.)
pre <- dm.[1:d]
post <- dm.[1:(d+1)]
pre.prod <- prod(pre)
post.prod <- prod(post)
all.prod <- prod(dm)
n.rep <- all.prod/post.prod
tmp1 <- (j)*pre.prod + (1:pre.prod)
tmp2 <- ((0:(n.rep-1))) * post.prod
addr <- outer(tmp1,tmp2,"+")
return(list(v=v[addr],dm=dm[-d]))
}
dm <- c(2^8,2^8,2^4,2^8)
ar <- array(1:prod(dm),dm)
d <- sample(1:length(dm),1)
j <- sample(1:dm[d],1)
out1 <- my.slice(c(ar),dm,d,j)
out2 <- my.slice.2(c(ar),dm,d,j)
plot(out2[[1]])