R相当于Matlab中的排列数组维度permute(A, dimorder)



我正在寻找从Matlab等效的permute(A,dimorder),以便将一些Matlab代码转换为R。一个循环包含这样一行:

x = permute(a{i}(b(i,ii),:,:,:,:,:),[2 3 4 5 6 1])

细胞数组结构(例如a{1}(1,:,:,:,:,:))导致选择细胞数组a{}内的第一行矩阵。permute()中的[2 3 4 5 6 1]dimorder。matlab函数permute()的文档包括示例输出可以在这里找到:https://de.mathworks.com/help/matlab/ref/permute.html

R中有几个函数以某种方式或另一种方式引用排列,但它们中没有一个似乎是我正在寻找的,尽管我可能犯了一些错误。

我相信我成功地复制了r中的MATLAB脚本。我认为您实际上不需要等效的permute。在MATLAB脚本中,permute似乎只是简单地删除多余的维度。R默认会这样做,除非你指定drop = FALSE作为数组子集,例如

lnA[[tau, modal]] <- a[[modal]][outcomes[modal, tau],,,drop = FALSE]

如果我在最终的for循环之前将lnA = cell(T, NumModalities);添加到MATLAB脚本中,然后将循环内部修改为

lnA{tau, modal} = permute(a{modal}(outcomes(modal,tau),:,:,:,:,:),[2 3 4 5 6 1]);

然后我得到lnA中相同的矩阵数组,用于MATLAB和R实现。

在R中,我使用列表数组作为MATLAB 2+维单元格数组的等效物:

lnA1 = cell(T, 1); # MATLAB
lnA1 <- vector("list", Time) # R    
lnA2 = cell(T, NumModalities); # MATLAB
lnA2 <- array(vector("list", Time*NumModalities), c(Time, NumModalities)) # R
lnA2 <- matrix(vector("list", Time*NumModalities), Time) # R
lnA3 = cell(T, NumModalities, 2); # MATLAB
lnA3 <- array(vector("list", Time*NumModalities*2), c(Time, NumModalities, 2)) # R

实现如下:

nat_log <- function (x) { # necessary as log(0) not defined...
x <- log(x + exp(-16))
}
# Set up a list for D and A
D <- list(c(1, 0),       # (left better, right better)
c(1, 0, 0, 0)) #(start, hint, choose-left, choose-right)
A <- c(rep(list(array(0, c(3, 2, 4))), 2), list(array(0, c(4, 2, 4))))
Ns <- lengths(D) # number of states in each state factor (2 and 4)
A[[1]][,,1:Ns[2]] <- matrix(c(1,1,  # No Hint
0,0,  # Machine-Left Hint
0,0), # Machine-Right Hint
ncol = 2, nrow = 3, byrow = TRUE)
pHA <- 1
A[[1]][,,2] <- matrix(c(0,       0,       # No Hint
pHA,     1 - pHA, # Machine-Left Hint
1 - pHA, pHA),    # Machine-Right Hint
nrow = 3, ncol = 2, byrow = TRUE)
A[[2]][,,1:2] <- matrix(c(1, 1,   # Null
0, 0,   # Loss
0, 0),  # Win
ncol = 2, nrow = 3, byrow = TRUE)
pWin <- 0.8
A[[2]][,,3] <- matrix(c(0,        0,         # Null        
1 - pWin, pWin,      # Loss
pWin,     1 - pWin), # Win
ncol = 2, nrow = 3, byrow = TRUE)
A[[2]][,,4] <- matrix(c(0,        0,        # Null        
pWin,     1 - pWin, # Loss
1 - pWin, pWin),    # Win
ncol = 2, nrow = 3, byrow = TRUE)
for (i in 1:Ns[2]) {
A[[3]][i,,i] <- c(1,1)
}
# Set up a list of matrices:
a <- lapply(1:3, function(i) A[[i]]*200)
a[[1]][,,2] <- matrix(c(0,    0,     # No Hint
0.25, 0.25,  # Machine-Left Hint
0.25, 0.25), # Machine-Right Hint
nrow = 3, ncol = 2, byrow = TRUE)
outcomes <- matrix(c(1, 2, 1,
1, 1, 2,
1, 2, 4),
ncol = 3, nrow = 3, byrow = TRUE)
NumModalities <- length(a)       # number of outcome factors
Time <- 3L
lnA <- array(vector("list", Time*NumModalities), c(Time, NumModalities))
for (tau in 1:Time){
for (modal in 1:NumModalities){
lnA[[tau, modal]] <- a[[modal]][outcomes[modal, tau],,]
}
}