slhck
slhck

Reputation: 38740

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?

Upvotes: 4

Views: 343

Answers (3)

Oli
Oli

Reputation: 16065

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

Upvotes: 4

Sam Roberts
Sam Roberts

Reputation: 24127

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.

Upvotes: 10

Rook
Rook

Reputation: 62568

Yes, although it is considered bad style (pedantic-wise), some people prefer not to have superfluous lines in their code.

Upvotes: 1

Related Questions