1 //
2 // polyfit_example.c
3 //
4 // Test polynomial fit to sample data.
5 //
6 
7 #include <stdio.h>
8 
9 #include "liquid.h"
10 
11 #define OUTPUT_FILENAME "polyfit_example.m"
12 
main()13 int main() {
14 
15     unsigned int n=15;      // number of samples
16     unsigned int order=2;   // polynomial order
17 
18     FILE * fid = fopen(OUTPUT_FILENAME, "w");
19     fprintf(fid,"%% %s : auto-generated file\n\n", OUTPUT_FILENAME);
20     fprintf(fid,"clear all;\nclose all;\n\n");
21 
22     // initialize data vectors
23     float x[n];
24     float y[n];
25     unsigned int i;
26     for (i=0; i<n; i++) {
27         float v = (float)(i) - (float)(n)/2 + 0.5f;
28         x[i] = v;
29         y[i] = v*v + randnf();
30 
31         printf("x : %12.8f, y : %12.8f\n", x[i], y[i]);
32         fprintf(fid,"x(%3u) = %12.4e; y(%3u) = %12.4e;\n", i+1, x[i], i+1, y[i]);
33     }
34 
35     // compute coefficients
36     unsigned int k=order+1;
37     float p[k];
38     polyf_fit(x,y,n,p,k);
39 
40     for (i=0; i<k; i++) {
41         printf("p[%3u] = %12.4e\n", i, p[i]);
42         // print polynomial coefficients vector in reverse order
43         fprintf(fid,"p(%3u) = %12.4e;\n", i+1, p[k-i-1]);
44     }
45 
46     // evaluate polynomial
47     float xmin = -7.5f;
48     float xmax =  7.5f;
49     unsigned int num_steps = 64;
50     float dx = (xmax-xmin)/(num_steps-1);
51     float xtest = xmin;
52     float ytest;
53     for (i=0; i<num_steps; i++) {
54         ytest = polyf_val(p,k,xtest);
55         fprintf(fid,"xtest(%3u) = %12.4e; ytest(%3u) = %12.4e;\n", i+1, xtest, i+1, ytest);
56         xtest += dx;
57     }
58 
59     // plot results
60     fprintf(fid,"plot(x,y,'x',xtest,ytest,'-');\n");
61     fprintf(fid,"xlabel('x');\n");
62     fprintf(fid,"ylabel('y, p^{(%u)}(x)');\n", order);
63     fprintf(fid,"legend('data','poly-fit',0);\n");
64     fprintf(fid,"grid on;\n");
65 
66     fclose(fid);
67     printf("results written to %s\n", OUTPUT_FILENAME);
68 
69     printf("done.\n");
70     return 0;
71 }
72 
73