The dimensions of B
can be anything you want. There is no set restriction in terms of size. For the Gaussian filter, it can be 1D, 2D or 3D. In 1D, what will happen is that each row gets filtered independently. In 2D, what will happen is that each slice gets filtered independently. Finally, in 3D you will be doing what is expected in 3D convolution. I am assuming you would like a full 3D convolution, not just 1D or 2D.
You may be interested in the output size of convn
. If you refer to the documentation, given the two N
dimensional matrices, for each dimension k
of the output and if nak
is the size of dimension k
for the matrix A
and nbk
is the size of dimension k
for matrix B
, the size of dimension of the output matrix C
or nck
is such that:
nck = max([nak + nbk - 1, nak, nbk])
nak + nbk - 1
is straight from convolution theory. The final output size of a dimension is simply the sum of the two sizes in dimension k
subtracted by 1. However should this value be smaller than either of nak
or nbk
, we need to make sure that the output size is compatible so that any of the input matrices can fit in the final output. This is why you have the final output size and bounded by both A
and B
.
To make this easier, you can set the size of the filter guided by the standard deviation of the distribution. I would like to refer you to my previous Stack Overflow post: By which measures should I set the size of my Gaussian filter in MATLAB?
This determines what the output size of a Gaussian filter should be given a standard deviation.
In 2D, the dimensions of the filter are N x N
, such that N = ceil(6*sigma + 1)
with sigma
being the desired standard deviation. Therefore, you would allocate a 3D matrix of size N x N x N
with N = ceil(6*sigma + 1);
.
Therefore, the code you would want to use to create a 3D Gaussian filter would be something like this:
% Example input
A = rand(3, 5, 6);
sigma = 0.5; % Example
% Find size of Gaussian filter
N = ceil(6*sigma + 1);
% Define grid of centered coordinates of size N x N x N
[X, Y, Z] = meshgrid(-N/2 : N/2);
% Compute Gaussian filter - note normalization step
B = exp(-(X.^2 + Y.^2 + Z.^2) / (2.0*sigma^2));
B = B / sum(B(:));
% Convolve
C = convn(A, B);
One final note is that if the filter you provide has any of its dimensions that are beyond the size of the input matrix A
, you will get a matrix using the constraints of each nck
value, but then the border elements will be zeroed due to zero-padding.