Suppose we have
Check.m:
classdef Check < handle
methods (Static)
function doStuff()
if isCalledFromAssertSubclass
% do this stuff only if called as Assert.doStuff(), not if called as Check.doStuff()
end
% do other stuff
end
end
end
and Assert.m:
classdef Assert < Check
% nop
end
As written in the comment, I would like to have that Check.doStuff() executes only the "do other stuff" line and that Assert.doStuff() executes the if isCalledFromAssertSubclass block as well.
I want to use static methods, so that I don't neet to create an Assert object whenever I need an assert. Using a global assert object is also very ugly and needs a global assert line in each function I want to use an assert. Likewise for checks.
So there are two problems:
Since these are static classes, there is no chance of using class(obj) or any other non-static class property or function.
dbstack is not inheritance aware and always returns Check as calling class, also for Assert.doStuff.
I did find a working solution, which uses a combination of dbstack and dbtype to read the line where the call came from, i.e. the line where it says Assert.doStuff(). However it involves two debug functions which probably should not be used in productive code and more importent, dbtype is very slow (in my case, 30 our of 70 seconds!).
I could use a package instead (directory +Check with function files in there) and create a symlink +Assert -> +Check. Then I could check the file name, but that's a) not portable, b) quite ugly and c) also somewhat slow (I suppose).
Is there any faster method for this?
Why not overload the static method for Assert, and have it call the parent's method when it's done? This is the normal way of using inheritance: you don't want the parent, Check, to know anything about its child, Assert.
This is what it would look like:
classdef Assert < Check
methods (Static)
function doStuff()
% do some stuff
Check.doStuff()
end
end
end
As #Wolfie suggests in a comment, the above works as long as Check.doStuff is not sealed. A sealed method cannot be overloaded. See the documentation.
When I was studying for my undergraduate degree in EE, MATLAB required each function to be defined in its own file, even if it was a one-liner.
I'm studying for a graduate degree now, and I have to write a project in MATLAB. Is this still a requirement for newer versions of MATLAB?
If it is possible to put more than one function in a file, are there any restrictions to this? For instance, can all the functions in the file be accessed from outside the file, or only the function that has the same name as the file?
Note: I am using MATLAB release R2007b.
The first function in an m-file (i.e. the main function), is invoked when that m-file is called. It is not required that the main function have the same name as the m-file, but for clarity it should. When the function and file name differ, the file name must be used to call the main function.
All subsequent functions in the m-file, called local functions (or "subfunctions" in the older terminology), can only be called by the main function and other local functions in that m-file. Functions in other m-files can not call them. Starting in R2016b, you can add local functions to scripts as well, although the scoping behavior is still the same (i.e. they can only be called from within the script).
In addition, you can also declare functions within other functions. These are called nested functions, and these can only be called from within the function they are nested. They can also have access to variables in functions in which they are nested, which makes them quite useful albeit slightly tricky to work with.
More food for thought...
There are some ways around the normal function scoping behavior outlined above, such as passing function handles as output arguments as mentioned in the answers from SCFrench and Jonas (which, starting in R2013b, is facilitated by the localfunctions function). However, I wouldn't suggest making it a habit of resorting to such tricks, as there are likely much better options for organizing your functions and files.
For example, let's say you have a main function A in an m-file A.m, along with local functions D, E, and F. Now let's say you have two other related functions B and C in m-files B.m and C.m, respectively, that you also want to be able to call D, E, and F. Here are some options you have:
Put D, E, and F each in their own separate m-files, allowing any other function to call them. The downside is that the scope of these functions is large and isn't restricted to just A, B, and C, but the upside is that this is quite simple.
Create a defineMyFunctions m-file (like in Jonas' example) with D, E, and F as local functions and a main function that simply returns function handles to them. This allows you to keep D, E, and F in the same file, but it doesn't do anything regarding the scope of these functions since any function that can call defineMyFunctions can invoke them. You also then have to worry about passing the function handles around as arguments to make sure you have them where you need them.
Copy D, E and F into B.m and C.m as local functions. This limits the scope of their usage to just A, B, and C, but makes updating and maintenance of your code a nightmare because you have three copies of the same code in different places.
Use private functions! If you have A, B, and C in the same directory, you can create a subdirectory called private and place D, E, and F in there, each as a separate m-file. This limits their scope so they can only be called by functions in the directory immediately above (i.e. A, B, and C) and keeps them together in the same place (but still different m-files):
myDirectory/
A.m
B.m
C.m
private/
D.m
E.m
F.m
All this goes somewhat outside the scope of your question, and is probably more detail than you need, but I thought it might be good to touch upon the more general concern of organizing all of your m-files. ;)
Generally, the answer to your question is no, you cannot define more than one externally visible function per file. You can return function handles to local functions, though, and a convenient way to do so is to make them fields of a struct. Here is an example:
function funs = makefuns
funs.fun1=#fun1;
funs.fun2=#fun2;
end
function y=fun1(x)
y=x;
end
function z=fun2
z=1;
end
And here is how it could be used:
>> myfuns = makefuns;
>> myfuns.fun1(5)
ans =
5
>> myfuns.fun2()
ans =
1
The only way to have multiple, separately accessible functions in a single file is to define STATIC METHODS using object-oriented programming. You'd access the function as myClass.static1(), myClass.static2() etc.
OOP functionality is only officially supported since R2008a, so unless you want to use the old, undocumented OOP syntax, the answer for you is no, as explained by #gnovice.
EDIT
One more way to define multiple functions inside a file that are accessible from the outside is to create a function that returns multiple function handles. In other words, you'd call your defining function as [fun1,fun2,fun3]=defineMyFunctions, after which you could use out1=fun1(inputs) etc.
I really like SCFrench's answer - I would like to point out that it can easily be modified to import the functions directly to the workspace using the assignin function. (Doing it like this reminds me a lot of Python's "import x from y" way of doing things)
function message = makefuns
assignin('base','fun1',#fun1);
assignin('base','fun2',#fun2);
message='Done importing functions to workspace';
end
function y=fun1(x)
y=x;
end
function z=fun2
z=1;
end
And then used thusly:
>> makefuns
ans =
Done importing functions to workspace
>> fun1(123)
ans =
123
>> fun2()
ans =
1
Along the same lines as SCFrench's answer, but with a more C# style spin..
I would (and often do) make a class containing multiple static methods. For example:
classdef Statistics
methods(Static)
function val = MyMean(data)
val = mean(data);
end
function val = MyStd(data)
val = std(data);
end
end
end
As the methods are static you don't need to instansiate the class. You call the functions as follows:
data = 1:10;
mean = Statistics.MyMean(data);
std = Statistics.MyStd(data);
I define multiple functions in one .m file with Octave and then use the command from within the .m file where I need to make use of the functions from that file:
source("mycode.m");
Not sure if this is available with Matlab.
octave:8> help source
'source' is a built-in function
-- Built-in Function: source (FILE)
Parse and execute the contents of FILE. This is equivalent to
executing commands from a script file, but without requiring the
file to be named `FILE.m'.
You could also group functions in one main file together with the main function looking like this:
function [varargout] = main( subfun, varargin )
[varargout{1:nargout}] = feval( subfun, varargin{:} );
% paste your subfunctions below ....
function str=subfun1
str='hello'
Then calling subfun1 would look like this:
str=main('subfun1')
As of R2017b, this is not officially possible. The relevant documentation states that:
Program files can contain multiple functions. If the file contains only function definitions, the first function is the main function, and is the function that MATLAB associates with the file name. Functions that follow the main function or script code are called local functions. Local functions are only available within the file.
However, workarounds suggested in other answers can achieve something similar.
I have try with the SCFRench and with the Ru Hasha on octave.
And finally it works: but I have done some modification
function message = makefuns
assignin('base','fun1', #fun1); % Ru Hasha
assignin('base', 'fun2', #fun2); % Ru Hasha
message.fun1=#fun1; % SCFrench
message.fun2=#fun2; % SCFrench
end
function y=fun1(x)
y=x;
end
function z=fun2
z=1;
end
Can be called in other 'm' file:
printf("%d\n", makefuns.fun1(123));
printf("%d\n", makefuns.fun2());
update:
I added an answer because neither the +72 nor the +20 worked in octave for me.
The one I wrote works perfectly (and I tested it last Friday when I later wrote the post).
I need to make a few constants accessible to my whole program (including classes). In C, I would put some #defines into a header file, and include it where I need the variables. Unfortunately, I do not see a way to do this in Matlab. Variables defined as global are not visible in classes.
So how can I do this?
globVar = someValue; // define globVar somewhere, somehow
classdef MyClass
// want to access globVar here
end
(I'm aware that global variables are bad design in many cases, but here they would be useful: It's about storing a list of commands of a communication protocoll.)
Will a class containing constant properties work in your case?
Here is example:
classdef Constants
properties (Constant)
pi_ = pi ;
golden_ = (1 + sqrt(5)) / 2 ;
end
end
You can access pi_ and golden_ anywhere in matlab code like this:
Constants.pi_
Constants.golden_
What is the meaning of the following folder names in MATLAB?
#folder
+folder
I've created a class Tata.m which uses the classdef syntax.
Should I put it in an #folder or a +folder?
I've looked at the documentation but it is not really clear
in which cases the #folder should be used and in which cases the +folder should be used.
The +folder piece is a MATLAB package folder. If you place Tata.m in a location like +folder/Tata.m, it will be known to MATLAB as the class folder.Tata. If you place it in a folder like someOtherFolder/Tata.m, or someOtherFolder/#Tata/Tata.m, it will be known to MATLAB as Tata.
It can be useful to place a classdef file in a class directory like #Tata to allow you to put the definition of some (or all) methods in separate files.
The doc has more details.
EDIT: To attempt to clarify the # directories: historically, a class Tata with methods methodOne and methodTwo would require the following files:
somePlaceOnThePath/#Tata/Tata.m
somePlaceOnThePath/#Tata/methodOne.m
somePlaceOnThePath/#Tata/methodTwo.m
In the "new" object system, you can still use the layout above without modification. At the other extreme, you can place the entire implementation of Tata in a single classdef block in:
somePlaceOnThePath/Tata.m
If you have some large methods, or want to split up the implementation of the class Tata into several files to make parallel development simpler, you can take use a classdef like this:
%# somePlaceOnThePath/#Tata/Tata.m:
classdef Tata
methods
result = methodTwo(obj, arg)
function methodOne(obj)
disp('hello from methodOne');
end
end
end
And also
%# somePlaceOnThePath/#Tata/methodTwo.m:
function result = methodTwo(obj, arg)
% do stuff with obj and arg
end
Strictly speaking, the advance declaration of methodTwo in the classdef is optional because it's using the default access specifiers. If you wanted to have methodTwo be a private method, you could place it in a methods (Access = private) block.
As noted here, functions in packages, as well as static methods in classes, still need to use a packagename.functionname syntax or import packagename.* for each function (since the imports are part of the function workspace and not global). This means that changing the package/class name later on can become a tedious nuisance.
Is there any way to do something like import this.*, i.e. a package/class name agnostic method to access all functions/static methods in the same package/class?
So... doesn't this require importthis to also be imported? Or is importthis a function you always have in your path?
It seems hardly more complex to just paste an "import this" block with this at the top of each function, and then you don't have to worry about importthis being in your path. I tend to feel that reliance on path is dangerous.
"Import This" block
%% Import own package
[~, pkgdir] = fileparts(fileparts(mfilename('fullpath')));
import([pkgdir(2:end) '.*']);
You can even put it in a try/catch block to make sure it's in a package directory, and decide what to do if it's not.
%% Import own package
try
[~, pkgdir] = fileparts(fileparts(mfilename('fullpath')));
import([pkgdir(2:end)'.*']);
catch err
if ~strcmp(err.identifier,'MATLAB:UndefinedFunction'), rethrow(err); end
end
I recently ran into a similar problem and found the following solution for packages. However it is VERY hacky.
You create a function called import this with an optional argument.
function to_eval = importthis(exclude_list)
if nargin == 0
exclude_list = [];
end
var_name = genvarname('A', exclude_list); %avoid shadowing
to_eval = ['[~,'...
, var_name...
, ']=fileparts(fileparts(mfilename(''fullpath'')));'... %get containing dir
, 'eval([''import '','...
, var_name...
, '(2:end),''.*'']);'... %remove '+'
, 'clear '... %clean up
, var_name
];
end
This function returns a string which can then be evaled that imports the "this" package. So in your package functions you would put the following near the top:
function B = myfunc(A)
eval(importthis);
%function body
end
You can also pass who to importhis, leaving your function's namespace clean.
function B = myfunc(A)
eval(importthis(who));
%function body
end
I can't decide whether I should feel proud or discusted by what I did.
This probably is not a bounty worthy answer but as you do not have any answers I thought I would post it anyway! You can invoke static methods via an instance of the class which you would only need to define once. You can invoke functions via a function handle but this would require one handle per function.
Using these techniques you could define all your static method and function references in one place. Then you would use these references throughout your package. Then if you decided to change the package name at a later point you would only need to update these references which are all stored in one place.
See:
Calling Static Methods
You can also invoke static methods using an instance of the class,
like any method:
obj = MyClass;
value = obj.pi(.001);
function_handle (#)
The following example creates a function handle for the humps function
and assigns it to the variable fhandle.
fhandle = #humps;