R中的多维数组索引与Matlab一样

时间:2017-04-28 20:15:38

标签: r matlab

我想问你一些看起来很简单的东西,但是我被卡住了...... 在Matlab页面中,它得到了很好的解释:https://www.mathworks.com/help/matlab/math/multidimensional-arrays.html

但是,我没有找到类似于R的东西。我的问题很简单:如何将这个Matlab代码转换为R?或者我如何打印矩阵每个维度的第一行元素,就像在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,:,:,:)

R中第一行的代码写成:

A<-array(1:84,c(3,7,4))

最后:B&lt; - ??

期望的结果是:

, , 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

提前谢谢!

1 个答案:

答案 0 :(得分:1)

Matlab使用A=[1:7;8:14;15:21];期间R中元素的行方式定义,在A<-array(1:84, c(3,7,4))中使用列式方式。这给出了期望的结果:

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

或相同:A[drop=FALSE, 1,,]