在n维数组上边缘化

drd*_*d13 8 multidimensional-array julia

我试图找出如何在朱莉娅处理多维数组.我有一个多维数组A = rand(5,5,5).

我试图找出如何获得A[1,1,:]A[1,:,1]A[:,1,1]与位置:由输入M给出.

我想出来了

indexData = [:,1,2]
indexData[1],indexData[m] = indexData[m],indexData[1]
data = A[indexData[1],indexData[2],indexData[3]]
Run Code Online (Sandbox Code Playgroud)

但这似乎过于复杂,如果维度A未知,则无法扩展.有没有更好的方法来解决这个问题?

Dan*_*etz 7

以下可能适合该法案:

getshaft(A,ii,m) = [A[(i==m?j:ii[i] for i=1:length(ii))...] for j=1:size(A,m)]
Run Code Online (Sandbox Code Playgroud)

请考虑以下示例:

julia> A = reshape(collect(1:27),3,3,3)
3×3×3 Array{Int64,3}:
[:, :, 1] =
 1  4  7
 2  5  8
 3  6  9

[:, :, 2] =
 10  13  16
 11  14  17
 12  15  18

[:, :, 3] =
 19  22  25
 20  23  26
 21  24  27

julia> getshaft(A,(1,2,3),1)
3-element Array{Int64,1}:
 22
 23
 24
Run Code Online (Sandbox Code Playgroud)

第二个参数是元素索引,第三个参数选择维度.getshaft将返回值向量,包括第二个参数沿第三个参数指定的维度选择的元素.第一个参数当然是数组.

---更新---

快速回顾一下,建议更快更清洁地实现相同的功能:

getshaft(A,ii,m) = A[(i==m?Colon():ii[i] for i=1:length(ii))...]
Run Code Online (Sandbox Code Playgroud)

使用切片索引可能会受益于更快的索引计算或后台的其他AbstractArray法术.