您知道 Matlab interp1 函数的任何 C 实现吗(只是“线性”函数)?我知道一个Java https://stackoverflow.com/questions/2986650/implementation-of-interp1-function-of-matlab-in-j2me.
我已将 Luis 的代码移植到 C++ 中。它似乎有效,但我没有检查太多,所以请注意并重新检查你的结果。
#include <vector>
#include <cfloat>
#include <math.h>
vector< float > interp1( vector< float > &x, vector< float > &y, vector< float > &x_new )
{
vector< float > y_new;
y_new.reserve( x_new.size() );
std::vector< float > dx, dy, slope, intercept;
dx.reserve( x.size() );
dy.reserve( x.size() );
slope.reserve( x.size() );
intercept.reserve( x.size() );
for( int i = 0; i < x.size(); ++i ){
if( i < x.size()-1 )
{
dx.push_back( x[i+1] - x[i] );
dy.push_back( y[i+1] - y[i] );
slope.push_back( dy[i] / dx[i] );
intercept.push_back( y[i] - x[i] * slope[i] );
}
else
{
dx.push_back( dx[i-1] );
dy.push_back( dy[i-1] );
slope.push_back( slope[i-1] );
intercept.push_back( intercept[i-1] );
}
}
for ( int i = 0; i < x_new.size(); ++i )
{
int idx = findNearestNeighbourIndex( x_new[i], x );
y_new.push_back( slope[idx] * x_new[i] + intercept[idx] );
}
}
int findNearestNeighbourIndex( float value, vector< float > &x )
{
float dist = FLT_MAX;
int idx = -1;
for ( int i = 0; i < x.size(); ++i ) {
float newDist = value - x[i];
if ( newDist > 0 && newDist < dist ) {
dist = newDist;
idx = i;
}
}
return idx;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)