%A cookbook approach to linear, least-squares fitting in Matlab % sample locations x = (0:5)' % simulated data g = x.*x % system matrix - value of terms in equaiton at sample locations H = [x.*x x (x*0 + 1)] % alternative way to fill constant column H = [x.*x x ones(size(x))] % try g = Hf --> %f = g/H % oops, should be f = H\g % I usually write it f = pinv(H)*g % order doesn't matter as long as measurements % are in matching position to rows of H % % supppose x = [x(3:end); x(1:2)] g = [g(3:end); g(1:2)] % have to make sure H is in proper order either by recreating as % done here, or reordering H = [x.*x x (x*0 + 1)] f = pinv(H)*g [x,y] = meshgrid( -1:.1:1 ) g = x.*x.*y + y.*y.*x + 1; mesh(x,y,g) % x, y and g are all 2D arrays, but we need vectors, that’s easy x = x(:) y = y(:) g = g(:) % Let’s fit to the equation % g = ax^2y + by^2x + cxy + dx^2 + ey^2 + fx + gy + h H = [x.*x.*y y.*y.*x x.*y x.*x y.*y x y (y*0+1)] f = pinv(H)*g % add some noise uniformly distributed +/- 0.025 n = (rand(size(g))-.5)*.05 gn=g+n; f = pinv(H)*g fn = pinv(H)*gn