Requirement:
write a function, input as node matrix, basis function, output image, display node and fitting curve;
Theory:
Least squares is a requirement that for a given data column, it is required
to find a function in a certain function class :,
such that Satisfying
According to the above conditions, it can be seen that the point
is
the minimum point of the multivariate function , which satisfies the equation system,
that is,
remember
, the above equation system can be expressed as, (k=0,1, …, n)
written in matrix form
, this equation is composed It is a system of normal equations. It can be proved that when
linearly independent, it has a unique solution.
In particular, a common case of curve fitting is algebraic polynomials, that is, take
, then
(k=0,1, …, n)
so the corresponding normal equations becomes
, This is the principle of least squares.
Matlab code:
①主函数
function u=OLSE_t(x,y,w,a)
syms b;
p=zeros(a,a);
f=zeros(a,1);
fai=zeros(a,length(x));
for m = 1:length(x)
fai(1,m)=log(x(m));
fai(2,m)=cos(x(m));
fai(3,m)=exp(x(m));
end
for i = 1:a
for j = 1:a
for m = 1:length(x)
p(i,j)=p(i,j)+w(m)*fai(i,m)*fai(j,m);
end
end
end
for i = 1:a
for m = 1:length(y)
f(i,1)=f(i,1)+w(m)*y(m)*fai(i,m);
end
end
u=res(p,f)
%计算平凡误差
det1=0;
det2=0;
for m = 1:length(y)
det1 = det1 + w(m)*y(m)^2;
for i = 1:a
det2=det2+u(i,1)*w(m)*y(m)*fai(i,m);
end
end
det = det1-det2
S=u(1,1)*log(b)+u(2,1)*cos(b)+u(3,1)*exp(b);
value=x(1):0.1:x(end);
S=subs(S,b,value);
plot(value,S);hold on;
plot(x(:),y(:),'*')
②线性方程求解
1)
function a=res(A,b)
n = length(A);
m = zeros(n);%存放行乘数
format long
for k = 1:n-1
temp = abs(A(k:n,k));%选主元比较的是绝对值的最大值
[value index] = max(temp);%选主元
u = index + k - 1;%调整为正确的最大行的索引
if u ~= k %选主元,换行
temp1 = A(u,k:n);
temp2 = b(u);
A(u,k:n) = A(k,k:n);
b(u) = b(k);
A(k,k:n) = temp1;
b(k) = temp2;
end
m(k+1:n,k) = A( k+1:n,k)/A(k,k);%计算行乘数
A(k+1:n,k:n) = A(k+1:n,k:n) - m(k+1:n,k)*A(k,k:n);
b(k+1:n) = b(k+1:n) - m(k+1:n,k)*b(k);
end
a=slo(A,b);
end
2)
function x=slo(A,b)
n = length(b);
x = zeros(n,1);
x(n) = b(n)/A(n,n);
if istriu(A)
for i = n-1:-1:1
x(i) = (b(i)-A(i,i+1:n)*x(i+1:n))/A(i,i);
end
else
disp("输入错误,请输入上三角")
end
disp('x=');
disp(x);
end
Program running results:
①The input is:
x=[0.24,0.65,0.95,1.24,1.73,2.01,2.23,2.52,2.77,2.99];
y=[0.23,-0.26,-1.10,-0.45,0.27,0.10, -0.29,0.24,0.56,1.00];
w=[1,1,0.8,0.9,1,1,1,1,0.9,0.9];
a=3;
u=OLSE_t(x,y,w,a)
The basis function is selected as
②The output result is: the
parameters to be determined are: the
square error is:
③The image of the curve of the fitting function is output: