如何在 Julia 的特定轴上对高阶多维数组(或张量)进行切片?
How can I slice the high-order multidimeonal array (or tensor) on the specific axis in Julia?
我正在使用Julia1.6
这里,X
是一个D
阶的多维数组。
如何在 X
的第 d
轴上从 i
切片到 j
?
这是 D=6
和 d=4
的例子。
X = rand(3,5,6,6,5,6)
Y = X[:,:,:,i:j,:,:]
i
和 j
给定的值在上面的例子中小于 6。
idx = ntuple( l -> l==d ? (i:j) : (:), D)
Y = X[idx...]
如果您只需要在单个轴上切片,请使用内置的 selectdim(A, dim, index)
,例如 selectdim(X, 4, i:j)
。
如果需要一次切片多个轴,可以通过先创建所有Colon
的数组,然后用指定的维度填充指定的维度来构建索引数组的数组指数。
function selectdims(A, dims, indices)
indexer = repeat(Any[:], ndims(A))
for (dim, index) in zip(dims, indices)
indexer[dim] = index
end
return A[indexer...]
end
您可以使用内置函数selectdim
help?> selectdim
search: selectdim
selectdim(A, d::Integer, i)
Return a view of all the data of A where the index for dimension d equals i.
Equivalent to view(A,:,:,...,i,:,:,...) where i is in position d.
Examples
≡≡≡≡≡≡≡≡≡≡
julia> A = [1 2 3 4; 5 6 7 8]
2×4 Matrix{Int64}:
1 2 3 4
5 6 7 8
julia> selectdim(A, 2, 3)
2-element view(::Matrix{Int64}, :, 3) with eltype Int64:
3
7
可以使用类似的东西:
julia> a = rand(10,10,10,10);
julia> selectedaxis = 5
5
julia> indices = 1:2
1:2
julia> selectdim(a,selectedaxis,indices)
请注意,在文档示例中,i 是一个整数,但您也可以使用 i:j
形式的范围。
我正在使用Julia1.6
这里,X
是一个D
阶的多维数组。
如何在 X
的第 d
轴上从 i
切片到 j
?
这是 D=6
和 d=4
的例子。
X = rand(3,5,6,6,5,6)
Y = X[:,:,:,i:j,:,:]
i
和 j
给定的值在上面的例子中小于 6。
idx = ntuple( l -> l==d ? (i:j) : (:), D)
Y = X[idx...]
如果您只需要在单个轴上切片,请使用内置的 selectdim(A, dim, index)
,例如 selectdim(X, 4, i:j)
。
如果需要一次切片多个轴,可以通过先创建所有Colon
的数组,然后用指定的维度填充指定的维度来构建索引数组的数组指数。
function selectdims(A, dims, indices)
indexer = repeat(Any[:], ndims(A))
for (dim, index) in zip(dims, indices)
indexer[dim] = index
end
return A[indexer...]
end
您可以使用内置函数selectdim
help?> selectdim
search: selectdim
selectdim(A, d::Integer, i)
Return a view of all the data of A where the index for dimension d equals i.
Equivalent to view(A,:,:,...,i,:,:,...) where i is in position d.
Examples
≡≡≡≡≡≡≡≡≡≡
julia> A = [1 2 3 4; 5 6 7 8]
2×4 Matrix{Int64}:
1 2 3 4
5 6 7 8
julia> selectdim(A, 2, 3)
2-element view(::Matrix{Int64}, :, 3) with eltype Int64:
3
7
可以使用类似的东西:
julia> a = rand(10,10,10,10);
julia> selectedaxis = 5
5
julia> indices = 1:2
1:2
julia> selectdim(a,selectedaxis,indices)
请注意,在文档示例中,i 是一个整数,但您也可以使用 i:j
形式的范围。