例如:
已知数据队列 buf=【5410.】
x取值 1:n n是队列长度
函数 f(x)=a+b*sin(c*x+d) .
avg 是队列平均值
a b c d 为参数 a范围 (2/3,1)*avg
b范围 (0,1/3)*avg
c的范围 (0,24*pi)
d (0,2*pi)
1、首先定义目标函数
function y=ga_curfit(x)
global ydata n
t=1:n;
y=0;
for i=1:n
y=y+(ydata(i)-(x(:,1)+x(:,2).*sin(x(:,3).*t(i)+x(:,4)))).^2/n;
end
y=sqrt(y);
end
2、把数据b.txt放在工作空间目录中
然后再命令窗口中输入
clear
global ydata n
format long g
load b.txt
ydata=b';
n=length(ydata);
avg=sum(ydata)/n;
LB=[2/3*avg 0 0 0];
UB=[1*avg 1/3*avg 24*pi 2*pi];
nvars=4;
options=gaoptimset;
options=gaoptimset(options,'PopulationSize',300);
options=gaoptimset(options,'CrossoverFraction',0.8);
options=gaoptimset(options,'MigrationFraction',0.1);
options=gaoptimset(options,'Generations',500);
options = gaoptimset(options,'TolFun',1e-50);
%options = gaoptimset(options,'InitialPopulation',final_pop);
options = gaoptimset(options,'Display','final');
options = gaoptimset(options,'PopInitRange',[LB;UB]);
options = gaoptimset(options,'PlotFcns',gaplotbestf);
options=gaoptimset(options,'Vectorize','on');%目标函数向量化
[x,fval,exitflag,output,final_pop,scores]=ga(ga_curfit,nvars,[],[],[],[],LB,UB,[],options);
t=1:n;
plot(t,ydata,'r*');
hold on
plot(t,x(1)+x(2)*sin(x(3)*t+x(4)))
legend('数据','拟合')