我创建了一个MyMex.m和一个MyMex.cpp。在.m内部,我使用mex编译.cpp。仅当.mex64不存在时才会发生。 .mex64符合Matlab PATH中的目录。但是如果我没有将Matlab当前工作目录设置为.mex64目录,那么Matlab将继续在无限循环上运行.m。我错过了什么?
MyMex.m:
function [dataOut] = MyMex(dataIn)
mexCppFile = 'MyMex.cpp';
mexCmd = 'mex MyMex.cpp;';
fprintf('\nFile %s not compiled yet, compiling it now...\n%s\n',mexCppFile,mexCmd);
fileFullPath = which(mexCppFile);
if size(fileFullPath,2) > 0 && exist(fileFullPath,'file')
[fileDir, fileName, ext] = fileparts(fileFullPath);
curDir = pwd;
cd(fileDir);
mex MyMex.cpp;
cd(curDir);
else
error('prog:input','Unable to find %s to compile it. Check if the file is in the current dir or in the Matlab PATH!',mexCppFile);
end
% Call C++ mex
[dataOut] = MyMex(dataIn)
end
编辑以保护自己免受我做无限循环的评论: Matlab应该知道该函数的编译版本。我不知道它是如何做到的,而且我的问题与此有关,因为有时候它会发现它的功能有时候并没有。
这是一个统一的在线mex样本,它做同样的事情" infinity"事情和工作顺利:
他在mirt2D_mexinterp.m中的代码:
% The function below compiles the mirt2D_mexinterp.cpp file if you haven't done it yet.
% It will be executed only once at the very first run.
function Output_images = mirt2D_mexinterp(Input_images, XI,YI)
pathtofile=which('mirt2D_mexinterp.cpp');
pathstr = fileparts(pathtofile);
mex(pathtofile,'-outdir',pathstr);
Output_images = mirt2D_mexinterp(Input_images, XI,YI);
end
也许.m和.mex64需要在同一个文件夹中。
答案 0 :(得分:2)
这一切都归结为Matlab's search path。 如果Mex文件位于路径中的同一级别,则它们优先于m文件。并且当前目录中的文件优先于在matlab搜索路径中的其他位置找到的文件。 因此,当您遇到无限循环时,很明显m文件在搜索路径中位于比mex文件更高的位置。
实质上,如果这两个文件位于同一文件夹中,则一切正常。