How to shadow the built-in find function
Show older comments
A while ago I have written a FEX submission that extends the capabilities of find to also work for 3D and up: findND (e.g. a syntax like [x,y,z,val]=findND(A)).
I would like to be able to shadow the built-in function, so I have the option of simply using [x,y,z,val]=find(A) in my code. My function would then use the code from this previous question to get a handle to the built-in function, so my function catches the call to find and does its thing if it needs to. Based on this question, I would have thought that it would be relatively easy to do this: just ignore the warning.
However, when I try this, it doesn't work: Matlab still calls the built-in function. list = which('find', '-all') shows my function as the first entry (for R2017b and R2012b).
It makes sense that Matlab would use the built-in, as that is the function precedence order, but in that case I don't understand why which would think that the local function would take precedence.
Is there a way to do this (preferably without requiring the end-user to jump through many hoops), or should I give up and just use my function under its own name?
3 Comments
Rik
on 5 Mar 2018
John D'Errico
on 5 Mar 2018
Weekends are slow.
Stephen makes good points here. Keeping them separate makes things simpler, and has many advantages. One more advantage is that the built-in find becomes a bit slower when you did just want to use it after all. Now you would have an additional layer of function overhead, tests, etc.
I would also add that the usual solution used, instead of needing a tool that grabs find as a function handle, is to use the builtin function. So at the point where you realize you really wanted to call the default find, just call it as
varargout = builtin('find',varargin{:});
That should grab the old find. What would not surprise me is if you needed to use the rehash command to make sure MATLAB sees your new find tool on the search path. If you don't use rehash, then even though which see your find, the toolbox cache is what matters in terms of what function is actually called.
Now, interestingly, I tested this all out with my own test version of find to see if I could overload find. My version of find just displayed some text to the command line, then used the function builtin to call find.
Assuming I would need to rehash the path, I did that, yet rehashing the cache, even restarting MATLAB, all failed to use my own version, consistent with what Rik observed.
Rik
on 5 Mar 2018
Accepted Answer
More Answers (0)
Categories
Find more on Entering Commands in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!