使用2D索引和1D向量访问3D矩阵

时间:2017-12-18 17:38:56

标签: matlab multidimensional-array indexing

我有一个3D矩阵A (size m*n*k)其中m =纬度,n *经度,k =时间。 我只想要第一维和第二维的特定值,由逻辑矩阵Bsize m*n)指定,我只想要由向量Csize k)指定的时间步长

最后这应该成为一个2D矩阵D,因为前两个维度将会折叠为一个。

最简单的方法是什么? 还有可能将逻辑与线性指标结合起来吗?例如,B是逻辑的,C是线性的吗?

使用rand的示例代码:

A=rand(10,10,10);
B=randi([0 1], 10,10);
C=randi([0 1], 10,1);
D=A(B,C) %This would be my approach which doesnt work. The size of D should be sum(B)*sum(c)

另一个没有rand的例子:

A=reshape([1:27],3,3,3);
B=logical([1,0,0;1,0,0;0,0,0]);
C=(1,3); %get data from timestep 1 and 5

D=A(B,C);%What I want to do, but doesnÄt work that way

D=[1,19;2,20];%Result should look like this! First dimension is now all data from dimesion 1 and 2. New dimesion 2 is now the time.

2 个答案:

答案 0 :(得分:2)

A = rand(4,4,4);
B = randi([0 1], 4,4)
B =
     1     1     0     1
     1     0     1     1
     0     0     1     0
     1     0     1     1

>> C = randi([0 1],1,1,4);
>> C(:)
ans =
     0
     1
     1
     0

然后使用bsxfun或隐式扩展扩展.*如果更新的Matlab版本为您给定坐标生成逻辑矩阵。

>> idx = logical(bsxfun(@times,B,C))

idx(:,:,1) =
     0     0     0     0
     0     0     0     0
     0     0     0     0
     0     0     0     0  
idx(:,:,2) =
     1     1     0     1
     1     0     1     1
     0     0     1     0
     1     0     1     1    
idx(:,:,3) =
     1     1     0     1
     1     0     1     1
     0     0     1     0
     1     0     1     1    
idx(:,:,4) =
     0     0     0     0
     0     0     0     0
     0     0     0     0
     0     0     0     0

然后您的输出为D = A(idx)。但请注意,此D现在是Nx1数组。其中N是真实元素的数量是B乘以C中真实元素的数量.10倍真实B和2倍真实C:

>> size(D)

ans =

    20     1

答案 1 :(得分:1)

一种简单的方法是先将reshape A放入m*n - by - k矩阵,然后执行indexing

result = reshape(A, [], size(A, 3));
result = result(B, C);

在这种情况下,C可以是逻辑向量或索引向量。