亲爱的 Stack 社区,
我正在做一个 DSP 练习,用在 Matlab 中设计并从中导出的滤波器系数来补充我的 C++ FIR 低通滤波器。所讨论的 DSP 练习是将 FIR 低通滤波器的输出阵列抽取到较低采样率“M”的行为。在 C++ 中,我在 .cpp 文件中实现了一个成功但极其简单的实现,并且我一直在努力将其转换为一个函数,我可以将 FIR 滤波器的输出数组提供给该函数。这是代码的最基本版本:
int n = 0;
int length = 50;
int M = 12;
float array[length];
float array2[n];
for (int i = 0 ; i<length; i++) {
array[i] = std::rand();
}
for (int i = 0; i<length; i=i+M) {
array2[n++] = array[i];
}
for (int i = 0; i<n; i++) {
std::cout << i << " " << array2[i] << std::endl;
}
如你所见,非常简单。不幸的是,我尝试将其转换为一个函数,但没有成功。这是原样的功能:
std::vector<float> decimated_array(int M,std::vector<float> arr){
size_t n_idx = 0;
std::vector<float> decimated(n_idx);
for (int i = 0; i<(int)arr.size(); i = i + M) {
decimated[n_idx++] = arr[i];
}
return decimated;
}
在 .cpp 文件中使用这部分代码时,这会产生一个非常常见的 Xcode 错误 EXC_BAD_ACCESS。错误发生在“decimated[n_idx++] = arr[i];”这一行具体来说:
int length = 50;
int M = 3;
std::vector<float> fct_array(length);
for (int i = 0 ; i<length; i++) {
fct_array[i] = std::rand();
}
FIR_LPF test;
std::vector<float> output;
output = test.decimated_array(M,fct_array);
我试图了解我的应用程序有什么不正确,或者可能只是我将算法转换为更通用的设置。任何对此问题的帮助将不胜感激,希望这足以让社区理解。
问候,Vhaanzeit
最佳答案
问题:
size_t n_idx = 0;
std::vector<float> decimated(n_idx);
您在使用 vector 之前没有确定 vector 的大小,因此在分配给 decimated
vector 的元素 0、1 等时调用了未定义的行为。
你本可以做的是在循环中,调用 push_back
:
std::vector<float> decimated_array(int M,std::vector<float> arr)
{
std::vector<float> decimated;
for (size_t i = 0; i < arr.size(); i = i + M) {
decimated.push_back(arr[i]);
}
return decimated;
}
decimated
vector 一开始是空的,但是通过 push_back
调用添加了一个新项目。
此外,您应该通过 const
引用而不是值来传递 arr
vector 。
std::vector<float> decimated_array(int M, const std::vector<float>& arr);
通过(常量)引用传递不会调用拷贝。
编辑:将循环计数器更改为正确的类型,因此不需要转换。
关于c++ - C++中的抽取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42729750/