MATLAB: Finding the maxima/minima of a function.

absolute valuemaximaminimaplot

My lab TA assigned a small project to find and plot the absolute value of the maxima and minima of a given function. I made a quick and dirty algorithm to do so, but I'm having two issues with it and I simply cannot figure out what is wrong with my code.
1.) For some reason, it isn't grabbing the actual highest value, but rather one close to it.
2.) The max/min plot dips down to nearly zero and then climbs up steadily with the Absolute valued function.
I know there are other ways of doing it, including using the derivative of the function, but I would much rather assistance in finding out what is incorrect in my algorithm, which tests surrounding points in order to find maxima and minima.
Here is the code:
________________
%This program plots the abs val of the maxima and minima of a function.
%This max/min value will then continue to be plotted until a new maxima or
%minima is found.
clear,clc;
t=[0:0.1:20];
y=exp(-t).*sin(pi./2.*t); %Our Function
yAbs=abs(y); %Take the absolute value of the function.
yMaxMin=zeros(201); %Create an array of zeros to be filled w/ data.
for(i=2:200)
%If a point is a maxima in yAbs, it will be a maxima or a minima in y.
if(yAbs(i-1)<yAbs(i)&&yAbs(i+1)>yAbs(i))
plotPoint=yAbs(i); %If the value is a max, store it in plotPoint.
end
yMaxMin(i)=plotPoint; %Store the value of plotPoint into yMaxMin(i)
end
plot(t,yAbs);
hold on
plot(t,yMaxMin);

Best Answer

You can use findpeaks function