If I have a single Matlab source file (m-file) containing a class definition (classdef), is there any way to specify a particular set of code that is to be executed if I run the m-file? I mean the entire file, such as via the Run button in the IDE, from a shell, or from the Matlab command-line. I don’t mean manually selecting the code to be executed.
Similar behaviour exists in Java with the static main method and in Python by having code outside the class definition (possibly inside a if __name__==__main__ block).
The short answer is “no”; MATLAB classdef M-files are just intended to define objects, not form complete programs.
The long answer is you might be able to get specific behavior out of your classdef function if, for example, you overload the constructor to take a flag specifying whether or not to “act like a variable” or “act like a program”.
e.g.
OR you can make a static method called main:
The IDE still won’t know what to do with your M-file to “run it”, but you can run it properly from the command line, or another M-file.
That last sentence is not 100% correct – as Egon pointed out below, you CAN make MATLAB’s IDE run that code – use a “run configuration”: http://www.mathworks.com/help/matlab/matlab_prog/run-functions-in-the-editor.html