Reputation: 45
I have two 2D matrices with the same number of columns, A
and B
. I want to convolve the corresponding columns of these two matrices and store the result into a new one call it result
. Assuming that result
has the appropriate dimensions, my current approach is something like:
for i = 1 : size( A, 2 ) % number of columns
result(:,i) = conv( A(:,i), B(:,i) );
end
Is there a way to avoid this loop using conv()
or perhaps conv2()
directly?
Upvotes: 1
Views: 980
Reputation: 112699
You can use the relationship between (circular) convolution and DFT, and exploit the fact that fft
, unlike conv2
, can work along a specified dimension:
A = rand(5,7);
B = rand(4,7); % example matrices. Same number of columns
s = size(A,1)+size(B,1)-1; % number of rows of result
result = ifft(fft(A,s,1).*fft(B,s,1));
Note that due to floating-point numerical precision there may be slight differences, of the order of eps
, between this result and that obtained with for
and conv
. In particular, if your inputs are real the result may have a (very small) imaginary part, so you may want to apply real
to the result.
Upvotes: 3
Reputation: 2930
If you want to use conv
function you can try conv(A_i,B_i, 'full')
but
you can also use below code for convolution, e.g. for column convolution convIt(A,B,1)
and for row convolution convIt(A,B,2)
function C = convIt(A,B,dim)
% the code is equivalent to running conv(A_i,B_i, 'full') in matlab
% (where A_i and B_i are columns (dim=1) or rows (dim=2) of A,B)
% and then stack the results together
if 1==dim || nargin<3 % default
A = [A;zeros(size(A))];
B = [B;zeros(size(B))];
elseif 2==dim
A = [A,zeros(size(A))];
B = [B,zeros(size(B))];
end
C = ifft(fft(A,[],dim).*fft(B,[],dim),[],dim);
if 1==dim || nargin<3 % default
C = C(1:end-1,:);
elseif 2==dim
C = C(:,1:end-1);
end
Upvotes: 0