How does MATLAB's $\tt upfirdn$ select extra points when downsampling? I had a signal 512 samples long and I used upfirdn to filter and downsample it by a factor of 2. I thought this would result in a 256 sample long variable, but instead it comes out as 261.  

The MATLAB help says this: 


  The length of the output, yout, is
  ceil(((length(xin)-1)*p+length(h))/q)


(where xin is the signal, h is the filter, p is the upsample ratio, and q is the downsample ratio) which, if you work it out (filter length is 10), does in fact come out to 261.  

What I want to know is how it selects points when downsampling so that I can reproduce the upfirdn behavior in another language (long story, not important). Where does that formula come from?
The function performs upsampling, filtering and downsampling. The reason for the extra samples is due to the fir filter delay. If you want to reproduce this behaviour for downsampling only you should do the following steps:


Take your input signal, xin and add length(h)-1 zeros at the end. This is done because of the filter's delay.
Use filter(h,1,xin_padded); to filter the signal.
Downsample the filtered signal.