MatLab中数据集的最大和最小点

时间:2012-04-16 02:02:39

标签: matlab max data-analysis

您好我正在尝试找到一种在MatLab中创建矩阵的方法,只需要在30秒的时间内重复练习的最大值和最小值。

例如,如果我有数据集:

data = [1 3 5 7 9 6 4 2 3 6 8 10 7 6 4 2 1]

我想要的结果是:

output = [1 9 2 10 1]

该功能仅绘制不断变化的波形的峰值。

我尝试过的代码如下:

size = length(data);    %Get the length of the dataset 
x = 1;                  %Set a counter value
maxplot = 0;            %Default, a maximum value has not yet been plotted

for x = 1:size-1
    a1 = data(1,x);     %Get two adjacent samples of the dataset
    a2 = data(1,x+1);

    v = 1;  %Set the initial column for the max points matrix

    while maxplot == 0
        if a1 > a2
            max(v,1) = a1;
            v = v + 1;
            maxplot = 1;
        end
    end

    if a1 < a2
        maxplot = 0;    
    end
end 

感谢任何提前回复的人,

贾里德。

2 个答案:

答案 0 :(得分:2)

您可以使用以下内容:

function Y = findpeaks(X)
    deltas = diff(X);
    signs = sign(deltas);
    Y = [true, (signs(1:(end-1)) + signs(2:end)) == 0, true];

findpeaks将返回与其输入X数组长度相同的逻辑数组。要提取标记值,只需按逻辑数组索引。

例如,

data = [1 3 5 7 9 6 4 2 3 6 8 10 7 6 4 2 1];
peaks = data(findpeaks(data))

应输出:

peaks =
    1    9    2   10    1

此函数不会对输入数组中的重复值执行任何特殊操作。我把它作为读者的练习。

答案 1 :(得分:2)

这个版本并不像John那样漂亮,但是当有平面部分时它不会失去高峰:

function peaks = findpeaks(data)
% Finds the peaks in the dataset

size = length(data);    %Get the length of the dataset 
x = 1;                  %Set a counter value
peaks = data(1,1);      %Always include first point

if size == 1  %Check for sanity
    return
end

lastdirection = 0;      %Direction of change

directions = sign( diff(data) ); %Directions of change
                                 % between neighboring elements

while x < size
    % Detect change in direction:
    if abs( directions(x) - lastdirection ) >= 2
        peaks = [peaks, data(1,x)];
        lastdirection = directions(x);
    else
        % This is here so that if lastdirection was 0 it would get
        % updated
        lastdirection = sign( lastdirection + directions(x) );
    end
    x = x+1;
end

peaks = [peaks, data(1,size)];
end