简体   繁体   中英

How to Convert Matrix Indexing Code from MATLAB to R

I have a one-dimensional matrix called h1 and a 3-dimensional matrix called nv in my MATLAB code. I then run the code h1(nv) to create a new 3 column matrix hc. I need to convert this code into R. I am not sure how to do this sort of matrix indexing in R. I thought you used brackets for matrix indexing so I tried just doing h1[nv] but that gave me a 1-dimensional array instead of 3 columns like my MATLAB output so it definitely isn't doing the same thing.

Frustratingly (personal opinion), R's arrays drop a dimension on indexing if the indexing reduces any of its dimensions to length-1.

For example:

m <- matrix(1:6, nrow=2)
m[1,]
# [1] 1 3 5
m[,2]
# [1] 3 4

This can be seen a little more clearly (perhaps) when looking at a 3-dim array:

ary <- array(1:24, dim=c(3,4,2))
ary
# , , 1
#      [,1] [,2] [,3] [,4]
# [1,]    1    4    7   10
# [2,]    2    5    8   11
# [3,]    3    6    9   12
# , , 2
#      [,1] [,2] [,3] [,4]
# [1,]   13   16   19   22
# [2,]   14   17   20   23
# [3,]   15   18   21   24

ary[1,,]
#      [,1] [,2]
# [1,]    1   13
# [2,]    4   16
# [3,]    7   19
# [4,]   10   22
ary[,2,]
#      [,1] [,2]
# [1,]    4   16
# [2,]    5   17
# [3,]    6   18

This can be avoided by adding ,drop=FALSE within the [ -indexing brackets:

m[1,,drop=FALSE]
#      [,1] [,2] [,3]
# [1,]    1    3    5
m[,2,drop=FALSE]
#      [,1]
# [1,]    3
# [2,]    4
ary[1,,,drop=FALSE]
# , , 1
#      [,1] [,2] [,3] [,4]
# [1,]    1    4    7   10
# , , 2
#      [,1] [,2] [,3] [,4]
# [1,]   13   16   19   22

(Note that you must include any intermediate unused commas, as n ary[1,,,drop=FALSE] . The drop= argument must always be in the (n+1) th position where the array has n dimensions.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM