Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to leave out "end" in MATLAB functions?

I'm totally new to MATLAB programming, but I received a script that somehow leaves out all the end statements for functions.

For example:

function pushbutton_open_Callback(hObject, eventdata, handles)
[FileName,PathName,FilterIndex] = uigetfile('*.txt','Select the CONFIG file');

if FileName~=0
    init_session(hObject, FileName, PathName);
end

% shouldn't there be an "end" here?

function pushbutton_start_Callback(hObject, eventdata, handles)
% ....

Is that syle "okay"? Apparently, there are no syntactic errors when I try to run it, and the program has worked whenever we've used it. Are functions automatically run until the next function statement?

like image 380
slhck Avatar asked Dec 06 '22 17:12

slhck


2 Answers

I would guess that in typical MATLAB code it's more common than not to leave out the ends. It's no problem to do that, but if you want to put them in that's fine too. I wouldn't say it's bad style to make either choice (FWIW, I usually leave them out).

There are some circumstances in which they have to be there, such as:

  1. If you're writing object-oriented code, method functions need to have an end
  2. Nested functions need to have an end
  3. If any function or subfunction in a file has an end, they all have to.

Since the typical piece of simple MATLAB code out there mostly has one function per file, maybe with some subfunctions, has no function nesting, and is not object-oriented, it will mostly leave out the ends.

like image 125
Sam Roberts Avatar answered Dec 21 '22 22:12

Sam Roberts


It's totally fine, matlab understantds that the end of the file is the end of the function. However, when you have several (nested) functions in the same file, you have to write end.

For instance:

function y=f(x)
  y=x^2+g(x)
  function y2=g(x2)
    y2=2*x2;
  end
end
like image 45
Oli Avatar answered Dec 22 '22 00:12

Oli