【问题标题】:Indexing for Multidimensional array in R like as MatlabR中多维数组的索引,如Matlab
【发布时间】:2017-04-29 05:07:30
【问题描述】:

我想问你一些看似简单但我卡住了... 在 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

想要的结果是:

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

提前感谢您!

【问题讨论】:

  • 我会添加想要的结果..

标签: r matlab


【解决方案1】:

Matlab 在R 中使用A=[1:7;8:14;15:21]; 中元素的行定义@ 在A&lt;-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,,]

【讨论】:

    猜你喜欢
    • 2015-03-10
    • 2014-11-15
    • 2013-06-30
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    • 2013-11-22
    相关资源
    最近更新 更多