Reputation: 2912
I am having following code, basically doing 1-d convolution on each row of a 2-D matrix. The convolution kernel is the same. So really the SIMD case.
a = [ 1,2,3,4,5;
6,7,8,9,7;
7,6,2,3,4;
23, 54, 1, 3 ,7];
f = [1,2,3];
for n = 1:size(a,1)
conv(a(n,:),f,'same')
end
When the matrix size(and the kernel size) gets larger, the speed really becomes a problem. I am wondering is there any way to this in batch (parallelize this process)?
I did something like this, but the results are different from above code:
a = [ 1,2,3,4,5;
6,7,8,9,7;
7,6,2,3,4;
23, 54, 1, 3 ,7];
f = [1,2,3];
ff = repmat(f, [size(a,1) 1]);
for n = 1:size(a,1)
conv(a(n,:),f,'same')
end
convn(a,ff,'same')
conv2(f,2,a,'same')
Please advise. Thanks.
PS: I am currently only seeking solution using convolution, not using fft equivalent.
Upvotes: 3
Views: 467
Reputation: 2431
You'll want to use a 2-dimensional convolution:
conv2(1, f, a, 'same')
or
conv2(a, f, 'same')
In the first method, the first argument is 1
because it's a column-wise convolution, and based on what you said, you only want to do row convolution, which is taken care of using the second argument, f
.
From the Matlab docs for conv2
:
C = conv2(H1, H2, A) first convolves each column of A with the vector H1 and then convolves each row of the result with the vector H2.
Convolving a scalar 1
along the columns is an identity operation, allowing the f
vector to convolve along the original matrix rows, which is the desired result.
For the second method above, this is a direct 2-dimensional convolution of the two input matrices, so if you take care to understand your input dimensions and argument order, this actually performs a faster operation.
Upvotes: 4