R 有一个包含 dtw 算法的包,但它非常慢,我决定用从这里用 C++ 编写的 dtw 替换它 。我马上说,我只是在学习编程,R 是我的第一语言,我不熟悉其他语言,尤其是 c++,所以如果我不懂,请不要感到惊讶有些东西,哪怕是非常微不足道的东西……
我需要从函数中获取两个任意长度的向量作为输入,并给出这些向量之间的欧几里德距离作为接近度的度量,就是这样......尽可能快和尽可能短
所以我从上面的链接中获取代码并尝试使用 Rccp 将其集成到 R 但是它没有用,在我看来,一开始声明变量及其类型是不正确的
#include <Rcpp.h>
using namespace Rcpp;
DEFUN_DLD (dtw3, args, , "Find DTW of two signals with window")
{
int nargin = args.length();
if (nargin != 2)
print_usage();
Matrix A = args(0).array_value();
Matrix B = args(1).array_value();
octave_stdout << "Size of A is " << A.length() << std::endl;;
octave_stdout << "Size of B is " << B.length() << std::endl;
if (! error_state)
{
octave_idx_type n = A.length();
octave_idx_type m = B.length();
Matrix results (n + 1, m + 1);
for(octave_idx_type i = 0; i <= n ; i++)
for(octave_idx_type j = 0; j <= m ; j++)
results(i, j) = octave_Inf;
results(0, 0) = 0;
octave_idx_type win = abs (n-m);
double cost = 0;
for(octave_idx_type i = 1 ; i <= n ; i++)
for(octave_idx_type j = std::max(1, i-win) ; j <= std::min(m, i+win) ; j++)
{
cost = abs(A(i-1) - B(j-1));
results(i, j) = cost + std::min(std::min(results(i-1,j),results(i,j-1)),results(i-1,j-1));
}
//octave_stdout << results << std::endl;
return ovl(results(n, m));
}
}
你能告诉我这段代码需要改变什么吗?
等效代码
Rcpp:该算法本身也在维基百科上有描述。