When looking for snippets of code for MATLAB and Octave I noticed that functions are ended in various ways, and all of them seem to work just fine. To be specific, I am talking about functions residing in their specific file.

MATLAB seems to end their functions with end.

function y = average(x) y = sum(x)/length(x); end 

Octave ends its functions with endfunction.

function retval = avg (v) retval = sum (v) / length (v); endfunction 

However, my functions work perfectly fine without any keyword at the end of the function.

So my question is, how strict are MATLAB/Octave with the endings of function definitions.

1 Answer

endfunction

  • endfunction is Octave-specific, and not valid MATLAB syntax (the same goes for endfor etc...)
  • If you know the code is only ever going to be run in Octave, then this syntax can make matching-up your loops/functions/... clearer and quicker. Just be aware your code is then MATLAB incompatible.
  • I believe you can also just use end in Octave for compatibility.

Strictness of using end

You may want to read the MATLAB documentation for nested functions

  • You don't have to end a function with the end statement when it is the only function in a file. From the docs:

    Typically, functions do not require an end statement.

  • Here is a related question on SO: Are multiple functions in one .m file nested or local when "end" isn't used, with the relevant excerpt being this, also from the docs:

    To nest any function in a program file, all functions in that file must use an end statement.

So in a function file with a sole function, the short answer is "not strict at all". However, it's good practise to use end so there is less ambiguity and more flexibility if you were to add other local functions.

4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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