按块

时间:2018-04-26 00:32:31

标签: matlab linear-regression

通过

生成函数sin (x) + 2;的25个点
xS = linspace (0.2 * pi, 25); 
yS = sin (xS) + 2;

找到以间隔调整前一曲线的线条,以使每个间隔中的误差小于5%。在点旁边绘制它们。 enter image description here

有人可以帮我这个程序吗?

我的节目:

线性回归函数:

function [m,b,error, yApp]=f_regresionLineal(x,y)
xp = mean(x);
yp = mean(y);
n = length(x);
m = ( sum(x.y) -nxpyp )/( sum(x.^2)-nxp^2 );
b = yp-m*xp;
yApp = m*x+b;
error = mean(abs(y-yApp)./y);
end

脚本:

S = linspace(0,2*pi,25);
yS = sin(xS)+2;
plot(xS,yS,'r*')
grid on
axis tight
hold on

xxS=xS(1:8);
yyS=yS(1:8);
[m,b,error, yApp]=f_regresionLineal(xxS,yyS)
hold on;
plot(xxS,yApp,'b');

xxS=xS(8:18);
yyS=yS(8:18);
[m,b,error, yApp]=f_regresionLineal(xxS,yyS)
hold on;
plot(xxS,yApp,'g');

xxS=xS(18:22);
yyS=yS(18:22);
[m,b,error, yApp]=f_regresionLineal(xxS,yyS)
hold on;
plot(xxS,yApp,'k');

xxS=xS(22:25);
yyS=yS(22:25);
[m,b,error, yApp]=f_regresionLineal(xxS,yyS)
hold on;
plot(xxS,yApp,'y');

1 个答案:

答案 0 :(得分:2)

首先,我必须说你的代码中存在很多错别字....

其次,在我看来,Piecewise linear regression是符合您需求的方法(抱歉,但我不确定这种方法的正确名称是英文)。

一些计算: enter image description here

所以我们选择将线性函数拟合到每三个点。

第三,下面的代码是你的一些扩展:

f_regresionLineal.m

function [m,b,error, yApp]=f_regresionLineal(x,y)

xp = mean(x); yp = mean(y); n = length(x);

m = (sum(x.*y)-n*xp*yp)/(sum(x.^2)-n*(xp^2)); 

b = yp-m*xp;

yApp = m*x+b; error = mean(abs(y-yApp)./y);

end

脚本:

clc; clear;
xS = linspace(0,2*pi,25)'; yS = sin(xS)+2;

plot(xS,yS,'r*'); 
grid on 
axis tight 
hold on

L=1:2:length(xS);
for ii=2:length(L)
  xxS=xS(L(ii-1):L(ii));
  yyS=yS(L(ii-1):L(ii));
  [m,b,error, yApp]=f_regresionLineal(xxS,yyS);
  plot(xxS,yApp,'b');
end

输出: enter image description here