Canoe
Comprehensive Atmosphere N' Ocean Engine
leastsq.c
Go to the documentation of this file.
1 #include <stdlib.h>
2 #include <string.h>
3 
4 #include "linalg.h"
5 
11 void leastsq(double **A, double *b, int n1, int n2) {
12  double *c = (double *)malloc(n1 * sizeof(double));
13  memcpy(c, b, n1 * sizeof(double));
14 
15  double **B;
16  B = (double **)malloc(n2 * sizeof(double *));
17  B[0] = (double *)malloc(n2 * n2 * sizeof(double));
18  for (int i = 0; i < n2; ++i) B[i] = B[0] + i * n2;
19 
20  for (int i = 0; i < n2; ++i) {
21  // calculate A^T.A
22  for (int j = 0; j < n2; ++j) {
23  B[i][j] = 0.;
24 #pragma GCC ivdep
25  for (int k = 0; k < n1; ++k) B[i][j] += A[k][i] * A[k][j];
26  }
27 
28  // calculate A^T.b
29  b[i] = 0.;
30 #pragma GCC ivdep
31  for (int j = 0; j < n1; ++j) b[i] += A[j][i] * c[j];
32  }
33 
34  // calculate (A^T.A)^{-1}.(A^T.b)
35  int *indx = (int *)malloc(n2 * sizeof(int));
36  ludcmp(B, n2, indx);
37  lubksb(B, n2, indx, b);
38 
39  free(c);
40  free(indx);
41  free(B[0]);
42  free(B);
43 }
#define A(i, j)
Definition: band_back_sub.c:18
void leastsq(double **A, double *b, int n1, int n2)
Definition: leastsq.c:11
void lubksb(double **a, int n, int *indx, double *b)
Definition: lubksb.c:14
int ludcmp(double **a, int n, int *indx)
Definition: ludcmp.c:14