我正在寻找一个等价物从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中有几个函数以这样或那样的方式引用排列,但它们似乎都不是我想要的,尽管我可能弄错了什么。
发布于 2021-10-21 14:47:41
我相信我已经成功地在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]);然后,对于MATLAB和R实现,我在lnA中得到了相同的矩阵数组。
在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],,]
}
}https://stackoverflow.com/questions/69661125
复制相似问题