MATLAB: How to plot all values in the IF loop

ifmaximumpeakplotwhile

I am writing a function, which cannot use the findpeaks or islocalmax, to plot all the maximum values on a graph. However with my if loop it plots each maximum value on a different figure
How do I display them all on one figure? Help very much appreciated.
Here is my function:
function [k] = Peak(X,Y)
for k = 2:length(Y)-1
if (Y(k) > Y(k-1) & Y(k) > Y(k+1) & Y(k) >100)
figure
plot(X,Y,X(k),Y(k),'r*')
end
end
end

Best Answer

Instead of the call to figure, call subplot() instead.
rows = ceil(sqrt(length(Y) - 2)); % Can put this line outside the loop
subplot(rows, rows, k-1); % In the loop, replace figure with this line.
This will make an array of several graphs (axes) all on the same figure.
If you want them all on the same graph/axes, then don't call subplot() at all, but call hold on after plot, and use && instead of &.
function [Peak] = findLocalMaxThreshold(X,Y)
for k = 2:length(Y)-1
if (Y(k) > Y(k-1) && Y(k) > Y(k+1) && Y(k) >100)
plot(X,Y,X(k),Y(k),'r*')
hold on;
end
end
hold off;
end