![](/img/trans.png)
[英]Call a function that is not on the Matlab path WITHOUT ADDING THAT PATH
[英]Is it possible to call a function that is not in the path in MATLAB?
我安裝了一個庫,它有一些與MATLAB同名的函數。 通過安裝lib,我的意思是addpath。 當我嘗試調用那些函數時,它將使用lib的實現,但我想調用MATLAB實現。
為了簡化:如果我有兩個函數的絕對地址,我如何指定調用哪個函數?
我搜索了答案,但我沒有在網站上找到它。
如果重載任何MATLAB內置函數來處理特定的類,那么MATLAB總是調用該類型的重載函數。 如果由於某種原因需要調用內置版本,則可以使用內置函數覆蓋通常的調用機制。 表達方式
builtin('reshape', arg1, arg2, ..., argN);
強制調用MATLAB內置函數,重新整形,傳遞顯示的參數,即使此參數列表中的類存在重載。
http://www.mathworks.com/help/techdoc/matlab_prog/br65lhj-1.html
使用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
當我將連續調用許多內置函數時,我喜歡的另一個問題的解決方案是暫時將我的庫移動到路徑的末尾。
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更頻繁地使用內置函數,你可以將庫保留在路徑的末尾,並在你使用它時將它移到頂部。 請注意當前目錄,但它始終優先於路徑順序。
安德烈的答案對我來說並不理想,但是它和洛倫的建議“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用戶:我建議謹慎使用這種方法! 在某些情況下它可能非常有用,但總的來說,我會問自己是否有更好的方法來處理你試圖解決的問題。 這可能會產生比解決更多的麻煩。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.