title: Harmonic Product Spectrum using MATLAB
body: <p>Im tying to find the fundamental frequency of a note using harmonic product spectrum. This is the part that implements the HPS algorithm</p>
  
  <pre><code>seg_fft = seg_fft(1 : size(seg_fft,1)/2 );  % FFT data
      seg_fft = abs(seg_fft);
  
      seg_fft2 = ones(size(seg_fft));
      seg_fft3 = ones(size(seg_fft));
      seg_fft4 = ones(size(seg_fft));
      seg_fft5 = ones(size(seg_fft));
  
      for i = 1:floor((length(seg_fft)-1)/2)
          seg_fft2(i,1) = (seg_fft(2*i,1) + seg_fft((2*i)+1,1))/2;
      end
  
  for i = 1:floor((length(seg_fft)-2)/3)
          seg_fft3(i,1) = (seg_fft(3*i,1) + seg_fft((3*i)+1,1) + seg_fft((3*i)+2,1))/3;    
      end
  
  for i = 1:floor((length(seg_fft)-3)/4)
          seg_fft4(i,1) = (seg_fft(4*i,1) + seg_fft((4*i)+1,1) + seg_fft((4*i)+2,1) + seg_fft((4*i)+3,1))/4;
      end
  
   for i = 1:floor((length(seg_fft)-4)/5)
          seg_fft5(i,1) = (seg_fft(5*i,1) + seg_fft((5*i)+1,1) + seg_fft((5*i)+2,1) + seg_fft((5*i)+3,1) + seg_fft((5*i)+4,1))/5;
      end
  
  f_ym = (seg_fft) .* (seg_fft2) .* (seg_fft3)  .* (seg_fft4) .*(seg_fft5);
  </code></pre>
  
  <p>Now when i play F4, the 2nd harmonic(698 -F5) has a higher amplitude. So HPS is supposed to help me detect the fundamental which is F4 and NOT F5.
  When i do the HPS these are the graphs I get:
  <img src="https://i.stack.imgur.com/FMdMe.jpg" alt="Plot of seg_fft2"><img src="https://i.stack.imgur.com/AQFxR.jpg" alt="seg_fft3"></p>
  
  <p><img src="https://i.stack.imgur.com/miKZt.jpg" alt="seg_fft4"></p>
  
  <p><img src="https://i.stack.imgur.com/ZZwF5.jpg" alt="seg_fft5"></p>
  
  <p>The figures above show the plots of seg_fft2, seg_fft3, seg_fft4 and seg_fft5 respectively.</p>
  
  <p>But what I dont understand is how come the frequency points obtained in these graphs are not factors of the original spectrum?? Isn't that how HPS is supposed to work??</p>
  
  <p>This is the plot I obtained when I took the product of all 5.<img src="https://i.stack.imgur.com/hjhSS.jpg" alt="enter image description here"> </p>
  
  <p>the peak is at 698Hz.. But shouldn't it be at 349Hz instead??</p>
  
  <p>But after the whole code is run, I do get the fundamental as F4.. Its all very confusing.... Can someone tell me why my graphs are different from what is expected yet I get the correct fundamental please????</p>
  
  <p>This is the rest of the code</p>
  
  <pre><code>    %HPS, PartIII: find max
       f_y1 = max(f_ym)
  
        for c = 1 : length(f_ym)
            if(f_ym(c,1) == f_y1)
                index = c;
            end
        end
  
        % Convert that to a frequency
        f_y(h) = (index / NFFT) * FS;
  
        h=h+1;
  
  %end
  
  V = abs(f_y);
  </code></pre>
  
  <p>Please do help...... Thanx in advance....</p>