Reputation: 23
I would like ask you something that seems simple but I got stuck... In Matlab page it is explained very well: https://www.mathworks.com/help/matlab/math/multidimensional-arrays.html
However, I didn't find something similar for R. My question is simple: how can I convert this Matlab code to R? Or how can I print the elements of the first row for each dimension of the matrix like as it is done in Matlab?
Matlab:
A=[1:7;8:14;15:21];
A(:,:,2)=[22:28;29:35;36:42];
A(:,:,3)=[43:49;50:56;57:63];
A(:,:,:4)=[64:70;71:77;78:84];
B=A(1,:,:,:)
The code of first rows in R is written:
A<-array(1:84,c(3,7,4))
The last: B<-??
The desired result is:
, , 1
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 1 2 3 4 5 6 7
, , 2
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 22 23 24 25 26 27 28
, , 3
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 43 44 45 46 47 48 49
, , 4
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 64 65 66 67 68 69 70
Thank you in advance!
Upvotes: 0
Views: 77
Reputation: 12559
Matlab uses rowwise definition of the elements in A=[1:7;8:14;15:21];
during R
uses columnwise in A<-array(1:84, c(3,7,4))
. This gives the desired result:
A <- array(NA, c(3,7,4))
A[,,1] <- matrix(c(1:7, 8:14, 15:21), 3, byrow=TRUE)
A[,,2] <- matrix(c(22:28, 29:35, 36:42), 3, byrow=TRUE)
A[,,3] <- matrix(c(43:49, 50:56, 57:63), 3, byrow=TRUE)
A[,,4] <- matrix(c(64:70, 71:77, 78:84), 3, byrow=TRUE)
A[1,, , drop=FALSE]
# > A[1,, , drop=FALSE]
# , , 1
#
# [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,] 1 2 3 4 5 6 7
#
# , , 2
#
# [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,] 22 23 24 25 26 27 28
#
# , , 3
#
# [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,] 43 44 45 46 47 48 49
#
# , , 4
#
# [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,] 64 65 66 67 68 69 70
or the same: A[drop=FALSE, 1,,]
Upvotes: 1