如何执行一维“有效"的步骤.卷积? [英] How to perform 1-dimensional "valid" convolution?
问题描述
我正在尝试在C ++中以有效"模式(Matlab定义)实现一维卷积.
I'm trying to implement a 1-dimensional convolution in "valid" mode (Matlab definition) in C++.
这似乎很简单,但是我一直无法找到使用C ++(或事实上我可以适应的任何其他语言)执行此操作的代码.如果矢量大小是幂,则可以使用2D卷积,但是我想找到适用于任何输入和内核的内容.
It seems pretty simple, but I haven't been able to find a code doing that in C++ (or any other language that I could adapt to as a matter of fact). If my vector size is a power, I can use a 2D convolution, but I would like to find something that would work for any input and kernel.
在给定大小为I的输入向量和大小为K的核的情况下,如何在有效"模式下执行一维卷积(输出通常应为大小为I-K +1的向量).
So how to perform a 1-dimensional convolution in "valid" mode, given an input vector of size I and a kernel of size K (the output should normally be a vector of size I - K + 1).
也接受伪代码.
推荐答案
您可以使用以下实现之一:
You could use the one of the following implementations:
template<typename T>
std::vector<T>
conv(std::vector<T> const &f, std::vector<T> const &g) {
int const nf = f.size();
int const ng = g.size();
int const n = nf + ng - 1;
std::vector<T> out(n, T());
for(auto i(0); i < n; ++i) {
int const jmn = (i >= ng - 1)? i - (ng - 1) : 0;
int const jmx = (i < nf - 1)? i : nf - 1;
for(auto j(jmn); j <= jmx; ++j) {
out[i] += (f[j] * g[i - j]);
}
}
return out;
}
f
:第一个序列(一维信号).
f
: First sequence (1D signal).
g
:第二序列(一维信号).
g
: Second sequence (1D signal).
返回大小为f.size() + g.size() - 1
的std::vector
,这是离散卷积的结果.柯西产品(f * g) = (g * f)
.
returns a std::vector
of size f.size() + g.size() - 1
, which is the result of the discrete convolution aka. Cauchy product (f * g) = (g * f)
.
template<typename T>
std::vector<T>
conv_valid(std::vector<T> const &f, std::vector<T> const &g) {
int const nf = f.size();
int const ng = g.size();
std::vector<T> const &min_v = (nf < ng)? f : g;
std::vector<T> const &max_v = (nf < ng)? g : f;
int const n = std::max(nf, ng) - std::min(nf, ng) + 1;
std::vector<T> out(n, T());
for(auto i(0); i < n; ++i) {
for(int j(min_v.size() - 1), k(i); j >= 0; --j) {
out[i] += min_v[j] * max_v[k];
++k;
}
}
return out;
}
f
:第一个序列(一维信号).
f
: First sequence (1D signal).
g
:第二序列(一维信号).
g
: Second sequence (1D signal).
返回大小为std::max(f.size(), g.size()) - std::min(f.size(), g.size()) + 1
的std::vector
,这是有效(即不带填充)离散卷积的结果.柯西产品(f * g) = (g * f)
.
returns a std::vector
of size std::max(f.size(), g.size()) - std::min(f.size(), g.size()) + 1
, which is the result of the valid (i.e., with out the paddings) discrete convolution aka. Cauchy product (f * g) = (g * f)
.
这篇关于如何执行一维“有效"的步骤.卷积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!