How to get a handle to an overriden built-in funct

2019-03-22 11:00发布

This question already has an answer here:

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).

2条回答
相关推荐>>
2楼-- · 2019-03-22 11:36

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).

查看更多
对你真心纯属浪费
3楼-- · 2019-03-22 11:53

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)

查看更多
登录 后发表回答