Search code examples
matlabplotfiguresmoothing

Findpeaks coordinates not matching X axis coordinates (Matlab)


I have a piece of code that is not performing as intended (at least in my view) and was hoping if someone could help clarify this issue.

The code plots a histogram of my data and the applies a ksdensity function to smooth the data, finally it runs a findpeaks function to return the max values plotted. However the coordinates for the horizontal axis do not correspond to the graphical representation of the plotted data.

MB(A); %array with the data to be plotted
figure;
histogram(MB(A),25)

[f,xi] = ksdensity(MB(A), 'Bandwidth',10);
figure;
plot(xi,f);
[peaks,loc] = findpeaks(f) 

the result from this piece of code are that:

peaks = 0.0232 0.0017
loc = 27 76

however when looking at the graphical representation the coordinates of the peaks (for the horizontal axis) are very different from these values

histogram smoothed data

I originally thought that might be a problem of over or under fitting but after playing around with the values a little bit the issue remained. Am I just missing some basic concept? Any help would be greatly appreciated. Many thanks


Solution

  • The [loc] location is the index of the point, so you would get the graphical x by:

    xi(loc)
    

    see matlab help for info on the returned variables:

    [PKS,LOCS]= findpeaks(Y) also returns the indices LOCS at which the
        peaks occur.