How to get a handle to an overriden built-in function? [duplicate]

情到浓时终转凉″ 提交于 2019-12-09 07:11:18

问题


On my Matlab path there's a custom zeros function. I want to store a handle to the built-in zeros in a variable. How can I do that?

Thought about @(varargin)builtin('zeros',varargin{:}), but this would probably slow down the operation due to the string comparison.

Also, I've noticed that it's possible to refer to diag as @numel\diag, but this doesn't seem to work with other built-in functions (zeros in particular).


回答1:


Well, this doesn't give you an exact answer to your question, but it could solve the problem:

I think this seems to be a good solution:

matlabcentral: How to call a shadowed function

Withn the last post:

Just stumbled upon this problem and found the following solution: For example, I have matlab svmtrain shadowed by libsvm toolbox:

which svmtrain -all

C:\Projects\Ichilov\Misc\MVPA\libsvm-mat-3.0-1\svmtrain.mexw64

C:\Program Files\MATLAB\R2009b\toolbox\bioinfo\biolearning\svmtrain.m % Shadowed

But I can access the original function by using str2func:

org_svmtrain = str2func([matlabroot '\toolbox\bioinfo\biolearning\svmtrain'])

and then simply calling:

org_svmtrain(training, groupnames)




回答2:


Suggestion #1

% At the beginning of your script:
rmpath('C:\the\folder\containing\the\custom\zeros');
builtInZeros = @zeros;
addpath('C:\the\folder\containing\the\custom\zeros');

% Calling the custom zeros later:
a = zeros(10, 20);

% Calling the built-in zeros:
b = builtInZeros(10, 20);

Suggestion #2

Put these three lines into your startup file:

rmpath('C:\the\folder\containing\the\custom\zeros');
builtInZeros = @zeros;
addpath('C:\the\folder\containing\the\custom\zeros');

Suggestion #3

It's definitely a dangerous idea to reuse the name of a built-in function. It ruins the readability of your scripts, making them much more difficult to maintain. So if you have control over the custom zeros function, then rename it to something else. Use a name which describes how the custom version is different from the built-in one (for example, call it fastZeros if it's faster).



来源:https://stackoverflow.com/questions/18206256/how-to-get-a-handle-to-an-overriden-built-in-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!