试图访问M(1,2);由于数字(M)= 1,因此索引越界

时间:2014-01-23 20:34:27

标签: matlab genetic-algorithm fuzzy-logic

我在Matlab中发现了一些关于比较GA(遗传算法)和ANFIS(自适应神经模糊推理系统)的代码。当我运行以下代码时,会发生以下错误:

  

试图访问M(1,2);由于数字(M)= 1,因此索引越界。   错误(第4行)
  M(1)= M(I,2);

由于我是Matlab的初学者,我无法找到问题所在。 这是代码:

function r=err(M)
for i=1:342;
    s(i)=M(i,1);
    m(i)=M(i,2);
    a(i)=M(i,3);
    b(i)=M(i,4);
end

dat=load('data2.txt','-ascii');
global X Y
X=0; Y=0;
X=dat(:,1);
Y=dat(:,2);


options = gaoptimset(@ga);
opts = gaoptimset(options,'PopulationSize',250);
options.PopInitRange = [0;5];
options.EliteCount = 1;
options.Generations = 250;
options = gaoptimset('PlotFcns', @gaplotbestf);
[param_ga fval] = ga(@temp , 10000 , [],[],[],[],[],[],[],options);

n_data=length(X);

err=0;
for ii=1:n_data
    for jj=1:342
        w(jj)=exp(-1*((X(ii)-param_ga((jj)*m(jj))/(param_ga((jj)*s(jj))))^2));
    end
    sum_w=sum(w);
    ww=w/sum_w;

    y=0;
    for jj=1:342
        y=y+ww(jj)*(param_ga((jj)*b(jj))+param_ga((jj)*a(jj))*X(ii));
    end

    err=err+(y-Y(ii))^2;
end

GA_AVERAGE_ERROR=err



numMFs = 10;
mfType = 'gauss2mf';
epoch_n = 500;
in_fis = genfis1(dat,numMFs,mfType,'linear');
[out_fis,error,stepsize]= anfis(dat,in_fis,epoch_n);

x=min(dat(:,1)):0.1:max(dat(:,1));
y=evalfis(x,out_fis);

yy=evalfis(dat(:,1),out_fis);
e=(yy-dat(:,2)).^2;
E=sum(e)/length(e);


ANFIS_AVERAGE_ERROR=E



if ANFIS_AVERAGE_ERROR>GA_AVERAGE_ERROR
    disp 'ANFIS_AVERAGE_ERROR > GA_AVERAGE_ERROR'
elseif ANFIS_AVERAGE_ERROR<GA_AVERAGE_ERROR
    disp 'ANFIS_AVERAGE_ERROR < GA_AVERAGE_ERROR'
else disp 'ANFIS_AVERAGE_ERROR = GA_AVERAGE_ERROR'
end

n=1:epoch_n;
y=x.^(2.5*sin(1*x))+x.^3-21*x.^2+99*x+21;


figure(1)
scatter(dat(:,1),dat(:,2))
hold on
plot(x,evalfis(x,out_fis),'-r','LineWidth',2);
plot(x,y,'-g','LineWidth',2);
hold off
legend('Training Data','ANFIS Output','Major Function');



disp('                     Result of Program                       ');


disp ('GA_AVERAGE_ERROR      =');disp(GA_AVERAGE_ERROR)
disp ('ANFIS_AVERAGE_ERROR   =');disp(ANFIS_AVERAGE_ERROR)

if ANFIS_AVERAGE_ERROR>=GA_AVERAGE_ERROR
    r=0;
else r=1;
end

if r==1
    disp 'ANFIS METHOD better than GENETIC ALGORITHM METHOD for this case'
else
    disp 'GENETIC ALGORITHM METHOD better than ANFIS METHOD for this case'
end

当我评论第4行第5行,第6行和第7行产生错误时。 感谢您的关注,感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

numel(M)= 1表示M是标量。因此,它没有条目M(1,2)。因此,您尝试访问第4行中不存在的条目会产生错误。