Reputation: 35321
I know that I can use a class consisting solely of static methods to implement a namespace in MATLAB. E.g.
classdef MyNamespace
methods (Static = true)
function [...] = foo(...)
...
end
function [...] = bar(...)
...
end
...
end
end
With the above I can call functions MyNamespace.foo
, MyNamespace.bar
, etc. (assuming, of course, that the file MyNamespace.m
is in my search path, or in the current directory).
A paramount feature of this technique is that it allows simulating "namespace variables". For example, a function within the methods (Static = true)
could have the form
function out = BAZ(newval)
persistent val;
out = val;
if nargin > 0, val = newval; end
end
With this, the method MyNamespace.BAZ
can mimic a "namespace variable" MyNamespace.BAZ
(though, admittedly, in a very cumbersome way).
This feature is one that I absolutely require.
The implementation of namespaces described above is ok, but I'd like to be able import namespace, so that I can call their functions using their "short" (aka "unqualified") names, such as foo
, bar
, etc.
How can I implement a namespace that can be imported, in the sense described above?
BTW, I'd prefer answers that build on the technique illustrated above (for implementing namespaces), since it's a technique I have some experience with, but I'm also open to alternatives that are not based on this technique.
Upvotes: 1
Views: 50
Reputation: 1928
MATLAB has a package system which allows creating a namespace of functions which are also importable. In short, just drop a directory whose name begins with a +
in another directory on your path and add your function MATLAB files in that directory. If you have MyNamespace.m
in the directory someDir
then just create:
someDir/+MyNamespace/foo.m
someDir/+MyNamespace/bar.m
and so on. You can call them via MyNamespace.foo, MyNamespace.bar
and import them:
import MyNamespace.foo
or:
import MyNamespace.*
Upvotes: 1