2

I'm trying to make a function in MATLAB for solving 2 equations using successive substitution. However, I am getting a nested function error( function NLSS), even though the function isn't nested. Here is the code:

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);
0

1 Answer 1

3

The function is nested because you have code before you use the function keyword. In MATLAB, you can not have a function inside a script. You can nest a function in another function and you can have a local function, which is declared after another function. A function must be in a file (strongly recommended that file name matches the function name) and the first line of that file is the function ... = ...(...) line. See the docs for more.

To fix your error, create a file called NLSS.m with the following code

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

And then change your original script to

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);

Note that you function has to be in your current working directory, i.e. the directory that your script is running from.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, your code worked. I just had to add ITEST in the output for the function code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.