如何用同名的新函数包装一个已经存在的函数 [英] How to wrap an already existing function with a new function of the same name

查看:82
本文介绍了如何用同名的新函数包装一个已经存在的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以围绕与原始函数名称完全相同的函数创建包装器?

Is it possible to create a wrapper around a function that has the exact same name as the original function?

在用户想要在将输入变量传递到内置函数

This would be very useful in circumstances where the user wants to do some additional checks on input variables before they are passed on to the built in function How to interrupt MATLAB IDE when it hangs on displaying very large array?

推荐答案

实际上,除了slayton的答案外,您无需使用openvar.如果您定义的函数与Matlab函数具有相同的名称,则该函数会遮住该函数(即改为调用).

Actually alternatively to slayton's answer you don't need to use openvar. If you define a function with the same name as a matlab function, it will shadow that function (i.e. be called instead).

为避免递归调用自己的函数,可以使用builtin从包装器中调用原始函数.

To then avoid recursively calling your own function, you can call the original function from within the wrapper by using builtin.

例如

outputs = builtin(funcname, inputs..);

一个简单的示例,名为rand.m,位于matlab路径中:

Simple example, named rand.m and in the matlab path:

function out = main(varargin)
disp('Test wrapping rand... calling rand now...');
out = builtin('rand', varargin{:});

注意,这仅适用于builtin找到的功能.对于那些没有的人,可能需要使用Slayton的方法.

Note that this only works for functions that are found by builtin. For those that are not, slayton's approach is likely necessary.

这篇关于如何用同名的新函数包装一个已经存在的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆