Home > front end >  iterating a three-dimensional array
iterating a three-dimensional array

Time:03-09

how can they iterate over the third dimension of an array? To examine all elements? For example:

v =  sample(1:5,24,replace = TRUE)
dim(v) = c(3,2,4)
print(v)

, , 1

     [,1] [,2]
[1,]    3    3
[2,]    4    5
[3,]    3    1

, , 2

     [,1] [,2]
[1,]    5    4
[2,]    4    3
[3,]    2    5

, , 3

     [,1] [,2]
[1,]    5    2
[2,]    5    5
[3,]    1    4

, , 4

     [,1] [,2]
[1,]    5    4
[2,]    1    3
[3,]    3    4

I would like to create a loop that iterates over the 4 matrices

CodePudding user response:

Try v[,,k] like below

for (k in 1:tail(dim(v), 1)) {
  print(v[, , k])
}
  • Related