How to End Matlab/Octave Function Definitions?

How to End Matlab/Octave Function Definitions?

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.
Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.