Does something like this exist? If not, can it be added to vnl_vector?


void TestProjectVector2D()
{

  vnl_vector<double> a(2);
  a(0) = 2;
  a(1) = -5;
  vnl_vector<double> b(2);
  b(0) = 5;
  b(1) = 1;
  vnl_vector<double> projection(2);
  vnl_vector<double> correct(2);
  correct(0) = 25./26.;
  correct(1) = 5./26.;
  ProjectVector2D(a,b,projection);

  std::cout << "Correct: " << correct << std::endl << "Actual: " << projection << std::endl;
}

bool ProjectVector2D(const vnl_vector<double> a, const vnl_vector<double> b, vnl_vector<double> &projection)
{
  // Project vector 'a' onto vector 'b' and store the result in 'projection'. If the projection is invalid, return false, else return true.

  bool invalid = false;
  if(a.size() != b.size())
    {
    invalid = true;
    }
    
  double bSquared = dot_product(b,b);

  if(bSquared == 0)
    {
    invalid = true;
    }

  if(invalid)
    {
    projection(0) = 0;
    projection(1) = 0;
    return false;
    }

  double scale = dot_product(a,b)/bSquared;

  for(unsigned int i = 0; i < a.size(); i++)
    {
    projection(i) = scale * b(i);
    }
  
  return true;
}

Thanks,

David