MATLAB: Lokal minimum and maximum

maximumminimum

I want to find the lokal minimum, and mark it in the plot. I succed in the first go, but in the second, not so good. For somereason it doesnt agree with me. Here is the code i type – I hope anyone can help me.
function opgave31
disp('opgave a')
title('a') x=(-5:5);
f=funktion(x);
plot(x,f)
hold on
y_ny=zeros(1,length(x));
plot(x,y_ny,'r')
x1=fzero(@funktion,-4); x2=fzero(@funktion,1); x3=fzero(@funktion,2);
plot(x1,y_ny,'b*',x2,y_ny,'b*',x3,y_ny,'b*')
close all
disp('opgave b')
title('b')
s=funktion2(x);
plot(x,s)
min=fminsearch(@funktion2,1,5)
max=fminsearch(@(x) -funktion2(x),-5,5)
x5=fzero(@funktion2,min); x6=fzero(@funktion2,max);
close all
plot(x,s,'r-',min,y_ny,'b*')
function y=funktion(x)
y=x.^3+x.^2-10*x+8
function t=funktion2(x)
t=x.^3-6*x.^2-x+30;

Best Answer

You can use findpeaks(y) to find maximums, and findpeaks(-y) to find minimums