Search code examples
matlabmaxdata-analysis

Maximum and minimum points of a dataset in MatLab


Hi I'm trying to find a way to create a matrix in MatLab with only the maximum and minimum values of an exercise repeated over a 30 second period.

For example, if I had the dataset:

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

My wanted outcome would be:

output = [1 9 2 10 1]

the function would only plot the peak values of a constantly changing waveform.

The code I've tried is as follows:

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 

Thanking whoever replies in advance,

Jared.


Solution

  • You could use something like this:

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

    findpeaks will return a logical array of the same length as its input X array. To extract the marked values, just index by the logical array.

    For example,

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

    Should output:

    peaks =
        1    9    2   10    1
    

    This function does not do anything special to cope with repeated values in the input array. I leave that as an exercise for the reader.