MATLAB Answers

0

enforcing that a class method is called instead of an "imported" function with the same name

Hi all,
I have a function called process(arg0, obj) that accepts two arguments. The second can be either a numeric matrix or an object of a custom made class (say, of class MyClass). The latter class has a method called dosomething. Within process(), I have the following code:
import MISC.dosomething;
dosomething(obj);
Where MISC is just a package where I have placed a function called dosomething (this is a normal function, not a method of any object). Obviously, what I want is that, if obj is of class MyClass, the class-associated method dosomething is called while, if obj is anything else but a MyClass object, the function MISC.dosomething is called. However, no matter what, function MISC.something is always called, even if obj is of class MyClass. I find this behavior rather counter-intuitive as I would expect that objects methods have higher preference than imported functions. Is there any way to enforce that MATLAB chooses object methods rather than an imported function that has the same name?
Thanks in advance.
Best,
Germán

  0 Comments

Sign in to comment.

2 Answers

Answer by Daniel Shub
on 21 Jul 2011
 Accepted Answer

I haven't read the documentation on "Scoping Classes with Packages"
but it seems relevant. More to the point, this piece of documentation says don't do what you are trying to do

  1 Comment

Thanks Daniel. I guess I will just have to check the type of the object and call to MISC.dosomething if the type is not myClass. The code is just a bit uglier but it's not a big deal.

Sign in to comment.


Answer by Jan
on 21 Jul 2011

The imported method is known at compile time (the time when the M-file is read and parsed - it is not "compiled" in a stricter definition), while the class of the object is determined at runtime only.
When I read the program, I'm be confused also. So I would not blame the JIT or the Matlab parser, but avoid the IMPORT of functions with ambigious names.
What happens, if you import the functions dynamically:
eval('import MISC.dosomething')
?? Just kidding - increasing the confusion level is not helpful...

  1 Comment

Thanks Jan. It makes sense but if I actually use the eval('import MISC.dosomething') it still calls MISC.dosomething which means that MATLAB loads the packages at runtime. It just happens that MATLAB gives preference to the package function, if the import command appears before the call to the dosomething method. Or am I wrong?

Sign in to comment.