1
+ function [x ] = lsquare_plot_with_qr(t , y , basis , plot_step )
2
+ % LSQUARE_PLOT_WITH_QR solve Ax = y for x in the least-square sense and
3
+ % plot the least-square fit using QR decomposition.
4
+ %
5
+ % INPUT
6
+ % t & y: m paired input cordinates
7
+ % basis: cell array of n basis function handles that have t as input
8
+ % these are used for forming A & plotting the least-square fit
9
+ % plot_step: (OPTIONAL) define the step for least-square fit plot,
10
+ % defaults to 0.01
11
+ % OUTPUT
12
+ % a plot of t & y and a least-square fit function for the data
13
+ % x: least-square fit solution of Ax = y
14
+
15
+ % validate and possibly default input
16
+ m = length(t );
17
+ assert(m > 0 , ' length of t must be > 0' )
18
+ assert(length(y ) == m , ' length of y should be same as t' )
19
+ n = length(basis );
20
+ assert(n > 0 , ' length of basis must be > 0' )
21
+ if nargin == 3 || plot_step == 0
22
+ plot_step = 0.01 ;
23
+ end
24
+
25
+ % form matrix A
26
+ A = zeros(m ,n );
27
+ for i = 1 : m
28
+ for j = 1 : n
29
+ A(i ,j ) = basis{j }(t(i ));
30
+ end
31
+ end
32
+
33
+ % find QR decomposition and w & U
34
+ [Q ,R ] = qr(A );
35
+ w = Q ' *y ;
36
+ w = w(1 : n , : );
37
+ U = R(1 : n , : );
38
+
39
+ % backward subs to solve x of Ux = w because U is upper triangular
40
+ x = zeros(n ,1 );
41
+ for i = n : - 1 : 1
42
+ other_terms = 0 ;
43
+ for j = n : - 1 : i + 1
44
+ other_terms = U(i ,j )*x(j ) + other_terms ;
45
+ end
46
+ x(i ) = (w(i ) - other_terms ) / U(i ,i );
47
+ end
48
+
49
+ % make the curve from basis functions
50
+ numbers = min(t ) : plot_step : max(t );
51
+ curve = x(1 ) * basis{1 }(numbers );
52
+ for i = 2 : n
53
+ curve = curve + x(i ) * basis{i }(numbers );
54
+ end
55
+
56
+ % plot the given data points and the curve
57
+ scatter(t ,y );
58
+ hold on
59
+ plot(numbers ,curve );
60
+ hold off
61
+
62
+ end
0 commit comments