【问题标题】:Sort each range of vector对向量的每个范围进行排序
【发布时间】:2018-09-05 10:50:32
【问题描述】:

给定以下向量:

5 4 1 2 3 1 4 5 3 2 3 2 1 5 4
_________ _________ _________

我想对向量的每 5 个元素应用排序。所以输出将是:

1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 
_________ _________ _________

在 MATLAB 中如何在没有循环的情况下实现这一点?

附:我还想提取排序索引以将它们应用于另一个向量。

【问题讨论】:

    标签: matlab sorting


    【解决方案1】:

    如果你想避免循环,你可以使用reshapesort 的组合来达到你想要的效果:

    b = [5 4 1 2 3 1 4 5 3 2 3 2 1 5 4];
    b2 = reshape(b, [5 3]);           % Reshape your array to be a [5x3] matrix
    b2_new = sort(b2, 1);             % Sort each column of your matrix seperately
    b_new = reshape(b2_new, size(b)); % Reshape the outcome back to the original dimensions
    

    或者,全部在一行中:

    b_new = reshape(sort(reshape(b, [5 3]), 1), size(b));
    

    当然,您必须更改数字 5 和 3 以适合您的问题。重要的是确保您为整形命令提供的第一个值(在本例中为 5)等于您要排序的子向量的长度,因为 Matlab 是主要列。

    编辑:

    如果您想对一个特定向量进行排序,然后对其他向量应用相同的重新排序,您可以使用sort 函数的可选第二个输出参数。使用与上述相同的向量:

    b = [5 4 1 2 3 1 4 5 3 2 3 2 1 5 4];
    b2 = reshape(b, [5 3]);
    

    产量:

    b2 = 5 1 3
         4 4 2
         1 5 1
         2 3 5
         3 2 4
    

    假设您要对第一列进行排序,并对第二列和第三列应用相同的重新排序,您可以这样做:

    [~,idx] = sort( b2(:,1) );   % Sorts the first column of b2, and stores the index map in 'idx'
    

    这将产生idx = [3 4 5 2 1]。现在您可以使用这些索引对所有列进行排序:

    b2_new = b2(idx,:);
    b2_new =
         1     5     1
         2     3     5
         3     2     4
         4     4     2
         5     1     3
    

    最后,您可以使用reshape 恢复原始尺寸:

    b_new = reshape(b2_new, size(b));
    

    编辑 2:

    如果您想将b 的重新排序作为一个整体存储,并将其应用到新的向量c,我们将不得不更有创意。以下是一种方法:

    b = [5 4 1 2 3 1 4 5 3 2 3 2 1 5 4];
    b2, = reshape(b, [5 3]);
    
    % Sort each column of your matrix seperately, and store the index map
    [~,idx] = sort(b2, 1);
    
    % Alter the index map, such that the indices are now linear indices:
    idx = idx + (0:size(idx,2)-1)*size(idx,1);
    
    % Reshape the index map to the original dimensions of b:
    idx = reshape(idx, size(b));
    
    % Now sort any array you want using this index map as follows:
    b_new = b(idx);
    c_new = c(idx);
    

    【讨论】:

    • 非常感谢!是否可以提取排序向量(重新整形)以将其应用于我需要以与对第一个向量排序相同的方式排序的另一个向量?
    • 我的意思是包含索引的排序函数的第二个输出。
    • 这是你的意思吗,Humam?我不完全确定。如果您想存储b 的整个重新排序,并将其应用到不同的向量c,我们将不得不更有创意。
    • 是的,我想要另一个选项。但是,从你的想法。我可以找到另一个问题的解决方案。我真的很感谢你的帮助!谢谢!
    • 啊,我想通了。没问题!我进行了第二次编辑,显示了您可以采取的一种方法。您也可以将其用作检查并自己尝试一些东西:-)
    猜你喜欢
    • 2021-12-10
    • 2015-06-03
    • 1970-01-01
    • 2015-08-16
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多