1

I've got some experience using octave. However, matlab is acting very differently. I've got this simple script:

function y=test(x)
    y=x*10;
end

a=test(10);

When I run it (that green 'play'-arrow in the GUI) it gives me the following error:

Error: File: TESTFILE.m Line: 5 Column: 1
This statement is not inside any function.
 (It follows the END that terminates the definition of the function "bla".)

What's wrong? Can't I just run a scipt where I use my own functions next to code not within a function?

1 Answer 1

1

The style of your code works in Python as well, but not in MATLAB. The error is giving you the answer This statement is not inside any function. You have three following solutions:

1- Either make a main function (this is in the same m-file)

function a=main()
    a=test(10);
end


function y=test(x)
    y=x*10;
end

2- Or save the function as test.m and use the last line to call your function from another script or from the command line.

3- You can also have nested functions (all in the same m-file):

function a=main()
    a=test(10);

    function y=test(x)
        y=x*10;
    end
end

Find very useful documentation and examples here.

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

6 Comments

option 1 is not working:Not enough input arguments. Error in mytest (line 2) y=x*10; Option 3 is working...very redundant though
because you do not see the output. add a as output and give it inputs if you like. The function here has no input argument but you can add by yourself. It 100% works by its current form though.
has it always been like that in matlab? octave accepts my code and I dont see any reason why matlab should not. Is there a reason at all?
The reason is when you make a function, MATLAB does not let you add some code outside of that function, unless that is another function. As I remember from 1994 MATLAB was like this, although we did not have nested functions then :)
ok. so i guess its also not possible to define functions in the command window?
|

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.