0

嗨,我正在尝试找到一种在 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 

感谢提前回复的人,

杰瑞德。

4

2 回答 2

3

你可以使用这样的东西:

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

这个函数没有做任何特殊的事情来处理输入数组中的重复值。我把它留给读者作为练习。

于 2012-04-16T02:12:26.973 回答
2

这个版本没有约翰的漂亮,但是当有平坦的部分时它不会失去峰值:

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
于 2012-04-16T03:09:05.490 回答