如何用matlab实现多项式拟合?要源代码已有数据x=[...],y=[...]离散数据
来源:学生作业帮助网 编辑:六六作业网 时间:2024/12/27 11:18:33
如何用matlab实现多项式拟合?要源代码已有数据x=[...],y=[...]离散数据
如何用matlab实现多项式拟合?要源代码
已有数据x=[...],y=[...]离散数据
如何用matlab实现多项式拟合?要源代码已有数据x=[...],y=[...]离散数据
我曾经写过的一个程序,
包含了画点,拟合,误差评估等
你相应的删减一些,
就能得到你需要的东西了.
希望能看的懂:
关键就一个函数:
a=polyfit(x,y,n);
请去matlab:
help polyfit
保证10分钟弄回自己的程序.
求人不如求己
% to find the least_squares fit for an input data set.
% to make a straigh line,and print it out.
% to deteming the constant m,b of y=mx+b.
%
%
clc; %clear the command window
clear;%clear all the variable has been defined
disp('----this program find the least_sqares fit of an input data set');
disp('---- as the form of y=a1*xn+a2*x(n-1)+.a(n)*x1+a(n+1)');
disp('------------starting!----------------');
%input data num
%input times of poly
x=input('enter the array of x like [1,2,3,4,.]:');
y=input('enter the array of y like [1,2,3,4,.]:');
n=input('enter times of polynomial like 2 :')
a=zeros(n+1);
%to count how many data in x
row_cloum=size(x);
m=row_cloum(2);
for i=1:1:m
plot(x(i),y(i),'bo');
hold on;
end
%calculate a
a=polyfit(x,y,n);
y_best=0;
%least squraus of ybest
%%plot the data input data as blue circles
% plot the line in red '-'
%create the fitted line of figture
xmin=min(x);
xmax=max(x);
t=xmin:0.01:xmax;
for i=1:(n+1)
y_a=(a(i)*(t.^((n+1)-i))); %element of y_poly_array
y_best=y_best+y_a; %sum them
end
% r the error array
for k=1:m
r_sum=0;
y_kbest=0;
for i=1:(n+1)
y_k(i)=(a(i)*(x(k).^((n+1)-i))); %element of y_k= ploy(xi)
y_kbest=y_kbest+y_k(i); %sum them ploy(xi)
end
r_sum=(y(k)-y_kbest)^2+r_sum;
end
%the poly is:
disp('the poly is y=a1*xn+a2*x(n-1)+.a(n)*x1+a(n+1):')
disp('and the array A is A=:');
disp(a);
disp('the (y_best-y)^2 is R= :')
disp(r_sum);
%figture
ymin=min(y_best);
ymax=max(y_best);
axis=([xmin,xmax,ymin,ymax]);
%set plot settings
%add a title and legend
plot(t,y_best,'r-','LineWidth',2);
%hold off;
title('\bf least-squares fit y=a1*xn+a2*x(n-1)+.a(n)*x1+a(n+1)');
xlabel('\bf\itx');
ylabel('\bf\ity');
legend('input data','fitted line',4);
grid on;
print -dtiff lsq_fit.tif;