I think I found a mistake in the code. Or at least something strange:
if foundPeak && (x(ii) > peakMag(end) || leftMin < peakMag(end)-thresh)
The second part, x(ii) > peakMag(end), is rather strange, since peakMag(end) will ALWAYS be equal to zero, since peakMag was preallocated with zeros. I guess this is a remainder from the time before you preallocated peakMag for speed.
I replaced the mistake with the following:
if foundPeak && (x(ii) > peakMag(cInd-1) || leftMin < peakMag(cInd-1)-thresh)
The strange thing is that the results luckily stay exactly the same, which is good but strange at the same time. There is probably some redundancy in the code.
In any case, your method was more or less what I was looking for. Just need to make some small adaptations to it for my purpose, of course leaving all credits to you. Thanks!