2014-01-23 22 views
-5

我在Matlab中找到了一些關於比較GA(遺傳算法)和ANFIS(自適應神經模糊推理系統)的代碼。當我運行以下代碼時,會發生此錯誤:試圖訪問M(1,2);指數越界,因爲numel(M)= 1

Attempted to access M(1,2); index out of bounds because numel(M)=1. Error in err (line 4)
m(i)=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行產生錯誤。 感謝您的關注,任何幫助表示讚賞。

+3

錯誤消息告訴你到底哪一行是問題。 –

+0

我知道。但究竟是什麼問題呢? –

+4

您是否嘗試過將342x4矩陣作爲參數而不是標量? – Notlikethat

回答

0

numel(M)= 1意味着M是一個標量。因此,它沒有條目M(1,2)。您嘗試訪問第4行中不存在的條目因此會產生錯誤。

相關問題