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.
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.
This version isn't as pretty as John's, but it doesn't lose peaks when there are flat parts:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.