在matlab中排序向量

时间:2013-03-19 17:14:56

标签: matlab

我有以下代码来计算峰值及其索引并显示它们,但我想对峰值进行排序并显示,所以我的代码如下:

function [peaks,peak_indices] = find_peaks(row_vector)
    A = [0 row_vector 0];
    j = 1;
    for i=1:length(A)-2
        temp=A(i:i+2);
        if(max(temp)==temp(2))
            peaks(j) = row_vector(i);

            peak_indices(j) = i;
            j = j+1;
        end
    end
end

通过以下方式实现之后,它显示了输出

A = [2 1 3 5 4 7 6 8 9];
>> [peaks, peak_indices] = find_peaks(A)

peaks =

     2     5     7     9


peak_indices =

     1     4     6     9

但是我不想直接显示峰值,而是想按降序显示峰值,或者像这样 9 7 5 2,我知道在matlab中存在函数排序,如下面的方式

b=[2 1 3 4 6 5];
>> sort(b)

ans =

     1     2     3     4     5     6

但是有两个问题,首先是按升序排序,还有如何在我的第一个函数中使用sort函数以递减的排序形式返回峰值?

1 个答案:

答案 0 :(得分:1)

你可以这样做:

peaks = sort(peaks, 'descend')

要分别重新订购peak_indices,请从sort获取已排序的索引:

[peaks, idx] = sort(peaks, 'descend');  %// Sort peaks
peak_indices = peak_indices(idx);       %// Reorder peak indices accordingly
相关问题