【问题标题】:Acces 3D Matrix with 2D index and 1D vector使用 2D 索引和 1D 向量访问 3D 矩阵
【发布时间】:2018-06-01 02:29:00
【问题描述】:

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

最后这应该成为一个二维矩阵 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.

【问题讨论】:

    标签: matlab multidimensional-array indexing


    【解决方案1】:
    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 或隐式扩展扩展 whith .* 如果较新的 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 中真实元素的数量。B 中为 10x True,C 中为 2x True:

    >> size(D)
    
    ans =
    
        20     1
    

    【讨论】:

      【解决方案2】:

      一种简单的方法是先将reshapeA 放入m*n-by-k 矩阵,然后再做indexing:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-20
        • 1970-01-01
        • 2016-04-24
        • 2015-07-30
        • 2018-01-02
        • 2011-08-04
        • 2022-10-15
        • 1970-01-01
        相关资源
        最近更新 更多