Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. // Polynomial regression function
  2. cv::vector fitPoly(cv::vector points, int n) {
  3.  
  4. //Number of points
  5. int nPoints = points.size();
  6.  
  7. // Vectors for all the points' xs and ys
  8. cv::vector xValues = cv::vector();
  9. cv::vector yValues = cv::vector();
  10.  
  11. // Split the points into two vectors for x and y values
  12. for(int i = 0; i < nPoints; i++) {
  13. xValues.push_back(points[i].x);
  14. yValues.push_back(points[i].y);
  15. }
  16.  
  17. //Augmented matrix
  18. double matrixSystem[n+1][n+2];
  19. for (int row = 0; row < n+1; row++) {
  20. for (int col = 0; col < n+1; col++) {
  21. matrixSystem[row][col] = 0;
  22. for (int i = 0; i < nPoints; i++) matrixSystem[row][col] += pow(xValues[i], row + col);
  23. }
  24.  
  25. matrixSystem[row][n+1] = 0;
  26. for (int i = 0; i < nPoints; i++) matrixSystem[row][n+1] += pow(xValues[i], row) ∗ yValues[i];
  27. }
  28.  
  29. //Array that holds all the coefficients
  30. double coeffVec[n+2];
  31.  
  32. //Gauss reduction
  33. for (int i = 0; i <= n − 1; i++)
  34. for (int k = i + 1; k <= n ; k++) {
  35. double t = matrixSystem[k][i] / matrixSystem[i][i];
  36. for (int j = 0; j <= n+1; j++) matrixSystem[k][j] = matrixSystem[k][j] − t ∗ matrixSystem[i][j];
  37. }
  38.  
  39. // Back−substitution
  40. for (int i = n; i >= 0; i−−) {
  41. coeffVec[i] = matrixSystem[i][n+1];
  42. for (int j = 0; j <= n+1; j++) if (j != i) coeffVec[i] = coeffVec[i] − matrixSystem[i][j] ∗ coeffVec[j];
  43.  
  44. coeffVec[i] = coeffVec[i] / matrixSystem[i][i];
  45. }
  46.  
  47. // Construct the cv vector and return it
  48. cv::vector result = cv::vector();
  49.  
  50. for (int i = 0; i < n+1; i++) result.push_back(coeffVec[i]);
  51. return result;
  52. }
  53.  
  54. // Returns the point f o r the equation determined
  55. //by a vector of coefficents, at a certain x location
  56. cv::Point pointAtX (cv::vector coeff, double x) {
  57. double y = 0;
  58. for (int i = 0; i < coeff.size(); i++) y += pow(x, i) ∗ coeff[i];
  59. return cv::Point(x, y);
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement