0

How can i write code after defining a function in matlab?

I would have separated them but I have to submit my homework as whole, one .m file.

It gives the following error "This statement is not inside any function.". I tried the answers in the web but it wont work.

My .m file starts with defining the function and after the end statement, after the definition I start writing my code. And I use my function defined above in the code

Thanks very much.

garagol
  • 31
  • 4
  • Please add your code as a [mcve] so we can see where it goes wrong. Without seeing your code though, I can already say you have to write **between** the `function` command and its related `end`. Everything after the end does not belong to the definition, since you *ended* that definition. – Adriaan Nov 03 '15 at 14:28
  • See: [local functions](http://www.mathworks.com/help/matlab/matlab_prog/local-functions.html) – sco1 Nov 03 '15 at 14:28

1 Answers1

3

You should do it the other way round.

Just wrap your 'normal' script in a function. Then, the other functions you can declare at the end of the file. E.g., if your file is called myHomework.m

function myHomework() % Should match the filename!
    n=6;
    if n>5
       x = someFunction(n);
       disp(x);
    end
end % Although this 'end' can usually be omitted, not now!

function out=someFunction(in)
    ...
end
Sanchises
  • 847
  • 4
  • 22
  • Filename and function name of the externally available function must match. – Daniel Nov 03 '15 at 14:31
  • 1
    '@Daniel I'll edit that in,thanks. Sometimes it's easy to forget the obvious. – Sanchises Nov 03 '15 at 14:32
  • 1
    Function `end` statements can be omitted as long as none of the functions in the file have them and there are no [nested functions](http://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html). Though this is the case I prefer to include them for readability. – sco1 Nov 03 '15 at 14:49
  • @excaza exactly. The way I posted this answer it's pretty much guaranteed not to break any of the original code, and an inadvertent extra 'end' will not cause all the functions to be interpreted as nested functions. – Sanchises Nov 03 '15 at 15:21