Julia-用向量提取多维矩阵的一部分



我正在尝试用向量来减少多维矩阵。

假设矩阵A是1000 x 10 x 100。向量b可以是100×1,其中100个条目是A的第一维的一部分。在A的第一维度的切片中总是恰好有一个元素与b的每个元素匹配。

如何将矩阵简化为匹配向量?

我试过

Ared= A[b,:,:]

但它不起作用。

本例中的新矩阵应具有100 x 10 x 100 的形式

有人有什么想法吗?

好吧,我想我明白你在问什么了。您正在查找findin()函数。它需要两个参数,每个参数都是一个集合。它查找第一个集合中第二个集合中的元素,并返回这些元素的索引。因此,我们可以将此函数应用于数组第一维的切片。下面是一些例子,为了简单起见,从2D开始,然后推广到3D,这实际上是基本相同的。

注意,有必要沿着第二维度和第三维度选择特定的索引(这里我为每个维度选择了1),因为否则,在第一维度切片中没有确定的元素可以与b的内容进行比较。(在这种情况下,每个维度只提供一组3个数字的一部分,这些数字一起标识3D阵列中的特定位置)。

b = rand(100);
using Distributions
indices = sample(1:1000, 100, replace=false) ## random indices for where the elements in a slice of the first dimension of A will match those in b.
## 2D example
A = rand(1000,100);
A[indices,1] = b; ## set 100 random rows of A will now have their first element match one element of b
Ared = A[findin(A[:,1], b),:]  ## find the rows in A where the first element is in B.  Return the full values of those rows.
## 3D example
A3 = rand(1000,10,100);
A3[indices,1,1] = b;
Ared3 = A3[findin(A[:,1,1], b),:,:];
julia> size(Ared3)
(100,10,100)

您的逻辑很好,如果b是一个向量,它就会工作。之所以没有,是因为你可能试图使用二维数组(即秩2)进行索引,而二维数组恰好只有一列,而不是向量(即秩1)数组。也就是说,我相信如果你做size(b),结果会是(2,1),而不是(2,),这是应该的。

如果您获得了b的相应向量(例如collect(b)),则索引操作应该可以正常工作。

示例:

julia> A = rand(Int64[1,10],3,4,2)
3x4x2 Array{Int64,3}:
[:, :, 1] =
 10  10   1  10
 10  10  10  10
  1  10  10   1
[:, :, 2] =
 1  10  10   1
 1  10   1   1
 1   1  10  10
julia> b = [1; 3]    # this will work. NOTE THE RESULTING TYPE!
2-element Array{Int64,1}:
 1
 3
julia> A[b,:,:]
2x4x2 Array{Int64,3}:
[:, :, 1] =
 10  10   1  10
  1  10  10   1
[:, :, 2] =
 1  10  10   1
 1   1  10  10
julia> c = [1 3]'    # this will not. NOTE THE RESULTING TYPE
2x1 Array{Int64,2}:
 1
 3
julia> A[c,:,:]
ERROR: MethodError: `index_shape_dim` has no method matching     index_shape_dim(::Array{Int64,3}, ::Int64, ::Array{Int64,2}, ::Colon, ::Colon)
julia> A[collect(c),:,:]    # this will work again, c is now a vector
2x4x2 Array{Int64,3}:
[:, :, 1] =
 10  10   1  10
  1  10  10   1
[:, :, 2] =
 1  10  10   1
 1   1  10  10

最新更新