title: Best way to perform a convolution with a new vector for each image?
body: <p>I try to figure out the best way to perform a kind of convolution.</p>
  
  <p>I have a 3D matrix I = [N x M x P] and a 2D matrix S = [1 x 1 x K x P]. For each pth frame (third dimension) of my 3D matrix I want to return the valid convolution between I(:, :, p-K/2:p+K/2) and S(1, 1, :, p). Do you see a way to do this ?</p>
  
  <p>In fact, in terms of computation the numbers of operation in very close to a standard convolution, the difference is that I need to change the second matrix for each frame...</p>
  
  <p>This is the method I currently use:</p>
  
  <pre><code>% I = 3D matrix [N x M x P]
  % S = Filter [1 x 1 x K x P] (K is an odd number)
  % OUT = Result
  
  [N, M, P] = size(I); % Data size
  K = size(S, 3); % Filter length
  win = (K-1)/2 ; % Window
  OUT = zeros(size(I)); % Pre-allocation
  
  for p = win+1:P-win
       OUT(:, :, p) = convn(I(:, :, p-win:p+win), S(1, 1, :, p), 'valid'); % Perform convolution
  end
  </code></pre>
  
  <p>At the end we have the same number of operations than the standard convolution, the only difference is that the filter is different for each frame...</p>
  
  <p>Any idea ?</p>
  
  <p>Thanks ;)</p>