【问题标题】:Sorting and indexing 3D arrays in MATLAB在 MATLAB 中对 3D 数组进行排序和索引
【发布时间】:2015-03-23 18:44:20
【问题描述】:

设 A 和 B 是相同大小的 3D 数组。我想对 A 的每一页进行排序,并(当然是快速有效地)置换 B,使其新索引对应于 A 的新索引,即我想让 Bs 条目以与 As 相同的方式排列。

天真的做法是做

  [sortedA,idx] = sort(A);
    newB=B(idx);

但是,这不起作用,因为 A(idx) 不等于 sortedA。 A(idx) 将所有页面复制到第一个排序页面。

这种情况有什么解决办法?

【问题讨论】:

    标签: matlab indexing


    【解决方案1】:

    Shot #1(沿每个 3D 页面/切片中的列排序)

    %// Get size of A
    [m,n,r] = size(A)
    
    %// Sort A along each column and get the corresponding sorting indices
    [sortedA,idx] = sort(A)
    
    %// Get the corresponding sorting indices for B and get the new B with them
    idxB = bsxfun(@plus,bsxfun(@plus,idx,[0:n-1]*m),permute([0:r-1]*m*n,[1 3 2]))
    newB = B(idxB)
    

    Shot #2(对每个 3D 页面/切片中的所有元素进行排序)

    %// Get size of A
    [m,n,r] = size(A)
    
    %// Reshape A into a 2D array and then sort it, and 
    %// also get the corresponding sorting indices
    [sortedA,idx] = sort(reshape(A,[],r)) 
    
    %// Get corresponding sorting indices for B, index into B with it,
    %// reshape it and have the desired re-arranged B
    idxB = bsxfun(@plus,idx,[0:r-1]*m*n)
    newB = reshape(B(idxB),size(B))
    

    【讨论】:

    • 第二个代码不起作用,例如,A=randn(2,1,2)。
    • @GregorianFunk 抱歉打错字了,现在看看?
    • @GregorianFunk 所以,您在寻找Shot #2 (Sorting for all elements in each 3D page/slice) 而不是Shot #1,对吗?请注意,这两个镜头会产生不同的结果。
    • 基本上我关心镜头 2,因为我的代码工作方式,但我也对一般答案感兴趣。由于 sort 命令适用于 2D 矩阵的方式,我认为可能有一种类似的方式来执行这两种操作。
    • @GregorianFunk 我不确定你这里的一般答案是什么意思,你能解释一下吗?
    猜你喜欢
    • 2022-09-23
    • 1970-01-01
    • 2011-08-04
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 2015-05-13
    相关资源
    最近更新 更多