2016-01-18 737 views
2

我想在MATLAB中使用連續替換來求解2個方程。但是,我得到一個嵌套的函數錯誤(函數NLSS),即使該函數沒有嵌套。下面是代碼:在matlab中嵌套的函數錯誤

X=[0.75 0.25]; %N-dimensional array, first guess then solution 

Y=[0 0]; 

G(1)=(sqrt(1-(X(2))^2)); %right hand side functions 
G(2)=1-X(1); %right hand side functions 

MAXIT=10; 

ITEST=1; 

function [X,counter] =NLSS(X,Y); 
    while ITEST==1 
     counter=0; 
     counter=counter+1; 
     X(1)=(sqrt(1-(X(2))^2)); 
     X(2)=1-X(1); 

      if abs(Y(1)-X(1))<0.00000001 
       ITEST=3; 
      end 

      if counter>MAXIT 
       ITEST=2; 
      end 

     Y(1)=X(1); 
     Y(2)=X(2);   

    end; 
end; 

fprintf('answer for X1 is %d and X2 is %d and ITEST is %d.\n',X(1),X(2),ITEST); 
fprintf('number of interations is %d.\n',counter); 

回答

3

函數嵌套,因爲你有代碼,您使用的功能關鍵字之前。在MATLAB中,你不能在腳本中使用函數。你可以在另一個函數中嵌套一個函數,並且你可以有一個本地函數,它是在另一個函數之後聲明的。函數必須位於文件中(強烈建議文件名與函數名匹配),該文件的第一行是function ... = ...(...)行。 See the docs瞭解更多信息。

要改正錯誤,創建一個名爲NLSS.m文件用下面的代碼

function [X,ITEST,counter] =NLSS(X,Y,ITEST,MAXIT); 
    while ITEST==1 
     counter=0; 
     counter=counter+1; 
     X(1)=(sqrt(1-(X(2))^2)); 
     X(2)=1-X(1); 

      if abs(Y(1)-X(1))<0.00000001 
       ITEST=3; 
      end 

      if counter>MAXIT 
       ITEST=2; 
      end 

     Y(1)=X(1); 
     Y(2)=X(2);   

    end 
end 

,然後改變你原來的腳本

X=[0.75 0.25]; %N-dimensional array, first guess then solution 

Y=[0 0]; 

G(1)=(sqrt(1-(X(2))^2)); %right hand side functions 
G(2)=1-X(1); %right hand side functions 

MAXIT=10; 

[X,ITEST,counter] =NLSS(X,Y,ISTEST,MAXIT); 

fprintf('answer for X1 is %d and X2 is %d and ITEST is %d.\n',X(1),X(2),ITEST); 
fprintf('number of interations is %d.\n',counter); 

請注意,您函數必須在你當前的工作目錄中,即你的腳本運行的目錄。

+1

謝謝,你的代碼工作。我只需在功能代碼的輸出中添加ITEST。 – user2606257