我安装了一个库,其中包含一些与MATLAB同名的函数。通过安装lib,我的意思是addpath。当我尝试调用这些函数时,它将使用lib的实现,但我想调用MATLAB实现。
为了简化:如果我有两个函数的绝对地址,我如何指定调用哪个函数?
我搜索了答案,但我没有在网站上找到它。
答案 0 :(得分:10)
如果重载任何MATLAB内置函数来处理特定的类,那么MATLAB总是调用该类型的重载函数。如果由于某种原因需要调用内置版本,则可以使用内置函数覆盖通常的调用机制。表达式
builtin('reshape', arg1, arg2, ..., argN);
强制调用MATLAB内置函数,重新整形,传递显示的参数,即使此参数列表中的类存在重载。
http://www.mathworks.com/help/techdoc/matlab_prog/br65lhj-1.html
答案 1 :(得分:8)
使用run
,它允许您使用自己的函数而不是内置函数,而无需将它们添加到路径中。
取自帮助:
运行不在当前路径上的脚本 语法
运行scriptname
正如@Cheery所说,它不能用于接受参数的函数。但是,run.m
是可修改的文件,因此我创建了一个可以接受参数的扩展版本。它也可以很容易地修改为输出参数。
function runExtended(script,varargin)
cur = cd;
if isempty(script), return, end
if ispc, script(script=='/')='\'; end
[p,s,ext] = fileparts(script);
if ~isempty(p),
if exist(p,'dir'),
cd(p)
w = which(s);
if ~isempty(w),
% Check to make sure everything matches
[wp,ws,wext] = fileparts(w);
% Allow users to choose the .m file and run a .p
if strcmp(wext,'.p') && strcmp(ext,'.m'),
wext = '.m';
end
if ispc
cont = ~strcmpi(wp,pwd) | ~strcmpi(ws,s) | ...
(~isempty(ext) & ~strcmpi(wext,ext));
else
cont = ~isequal(wp,pwd) | ~isequal(ws,s) | ...
(~isempty(ext) & ~isequal(wext,ext));
end
if cont
if exist([s ext],'file')
cd(cur)
rehash;
error('MATLAB:run:CannotExecute','Can''t run %s.',[s ext]);
else
cd(cur)
rehash;
error('MATLAB:run:FileNotFound','Can''t find %s.',[s ext]);
end
end
try
feval(s,varargin{:});
% evalin('caller', [s ';']);
catch e
cd(cur);
rethrow(e);
end
else
cd(cur)
rehash;
error('MATLAB:run:FileNotFound','%s not found.',script)
end
cd(cur)
rehash;
else
error('MATLAB:run:FileNotFound','%s not found.',script)
end
else
if exist(script,'file')
evalin('caller',[script ';']);
else
error('MATLAB:run:FileNotFound','%s not found.',script)
end
end
end
答案 2 :(得分:2)
当我连续调用很多内置函数时,我喜欢你的问题的另一个解决方案是暂时将我的库移动到路径的末尾。
libpath = '/home/user/mylib';
% move mylib to the end of the path
addpath(libpath, '-end');
% now call some built-in functions that mylib overwrites
reshape(rand(100),10,10);
% return mylib to the top
addpath(libpath)
当然,如果您使用内置函数比使用libary更频繁,则可以将库保留在路径的末尾,并在您使用它时将其移至顶部。请注意当前目录,但是,路径顺序总是需要precedence。
答案 3 :(得分:1)
安德烈的答案对我来说并不理想,但它和洛伦的建议是“cd到目录,创建 你的函数句柄,然后回来“让我想到以下内容:
定义一个执行Loren描述的函数:
function functionHandle = getFunctionHandleFromFile( fullFileName )
[pathstr, name, ext] = fileparts(fullFileName);
prevDir = pwd;
cd(pathstr);
functionHandle = str2func(name);
cd(prevDir);
然后你可以用它来获取句柄。使用句柄,您可以调用函数:
nameOf = getFunctionHandleFromFile('/Users/sage/matlab-utilities/nameOf.m')
nameOf(output)
注意新的MATLAB用户:我建议谨慎使用这种方法!在某些情况下它可能非常有用,但总的来说,我会问自己是否有更好的方法来处理你试图解决的问题。这可能会产生比解决更多的麻烦。