Reputation: 5294
I created a MyMex.m and a MyMex.cpp. Inside the .m I compile the .cpp using mex. It should happen only if the .mex64 does not exists. The .mex64 is complite to a directory in Matlab PATH. But Matlab will keep running the .m on an infinity loop if I don't set the Matlab current working dir to the .mex64 dir. What I'm missing?
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
Edit to defend myself from the comments that I did a infinity loop: Matlab was supposed to know that there is a compiled version of the function. I don't know how it does it and my problem is related to that, since some times it finds the function some times it doesn't.
Here is a consolidated online mex sample that does the same "infinity" thing and work smoothly:
His code in 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
Maybe the .m and the .mex64 need to be on the same folder.
Upvotes: 3
Views: 324
Reputation: 7017
It all comes down to Matlab's search path. Mex-files are prioritized over m-files if they are on the same level in the path. And files in the current directory take precedence over files found elsewhere in the matlab search path. So when you experience an infinite loop, it is clear that the m-file is locate higher in the search path than the mex-file.
In essence, all is fine if the two files are in the same folder.
Upvotes: 2