%% Find Peaks with Minimum Separation
% Sunspots are a cyclic phenomenon. Their number is known to peak roughly every 11 years.
% Load the file sunspot.dat, which contains the average number of sunspots observed every year from 1700 to 1987. Find and plot the maxima.

load sunspot.dat

year = sunspot(:,1);
avSpots = sunspot(:,2);

findpeaks(avSpots,year)

%
% Improve your estimate of the cycle duration by ignoring peaks that are very close to each other. Find and plot the peaks again, but now restrict the acceptable peak-to-peak separations to values greater than six years.

findpeaks(avSpots,year,'MinPeakDistance',6)

%
% Use the peak locations returned by findpeaks to compute the mean interval between maxima.

[pks,locs] = findpeaks(avSpots,year,'MinPeakDistance',6);

meanCycle = mean(diff(locs))

%
% Create a datetime array using the year data. Assume the sunspots were counted every year on March 20th, close to the vernal equinox. Find the peak sunspot years. Use the years function to specify the minimum peak separation as a duration.

ty = datetime(year,3,20);

[pk,lk] = findpeaks(avSpots,ty,'MinPeakDistance',years(6));

plot(ty,avSpots,lk,pk,'o')

%
% Compute the mean sunspot cycle using datetime functionality.

dttmCycle = years(mean(diff(lk)))

%
% Create a timetable with the data. Specify the time variable in years. Plot the data. Show the last five entries of the timetable.

TT = timetable(years(year),avSpots);
plot(TT.Time,TT.Variables)
entries = TT(end-4:end,:)

% Copyright 2012 The MathWorks, Inc.