有没有一种方法可以使用 conv() 在 MATLAB 中执行逐列卷积?
Is there a way to perform column-wise convolution in MATLAB using conv()?
我有两个具有 相同列数 、A
和 B
的二维矩阵。我想对这两个矩阵的相应列进行卷积并将结果存储到一个新的矩阵中,称之为 result
。假设 result
具有适当的尺寸,我目前的方法是这样的:
for i = 1 : size( A, 2 ) % number of columns
result(:,i) = conv( A(:,i), B(:,i) );
end
有没有办法直接使用 conv()
或者 conv2()
来避免这个循环?
如果你想使用 conv
功能你可以尝试 conv(A_i,B_i, 'full')
但是
您还可以使用以下代码进行卷积,例如对于列卷积 convIt(A,B,1)
和行卷积 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
您可以使用(循环)卷积和 DFT 之间的关系,并利用 fft
, unlike conv2
可以沿指定维度工作的事实:
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));
请注意,由于浮点数值精度,结果可能存在 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
级的细微差异。
我有两个具有 相同列数 、A
和 B
的二维矩阵。我想对这两个矩阵的相应列进行卷积并将结果存储到一个新的矩阵中,称之为 result
。假设 result
具有适当的尺寸,我目前的方法是这样的:
for i = 1 : size( A, 2 ) % number of columns
result(:,i) = conv( A(:,i), B(:,i) );
end
有没有办法直接使用 conv()
或者 conv2()
来避免这个循环?
如果你想使用 conv
功能你可以尝试 conv(A_i,B_i, 'full')
但是
您还可以使用以下代码进行卷积,例如对于列卷积 convIt(A,B,1)
和行卷积 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
您可以使用(循环)卷积和 DFT 之间的关系,并利用 fft
, unlike conv2
可以沿指定维度工作的事实:
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));
请注意,由于浮点数值精度,结果可能存在 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
级的细微差异。