How Matlab knows there is a .mex64 file and to avoid endless "compile" loop

I created MyMex.m and MyMex.cpp. Inside .m I am compiling .cpp using mex. This should only happen if .mex64 does not exist..mex64 matches a directory in Matlab's PATH. But Matlab will keep running .m in an endless loop if I don't set the current Matlab working directory to the .mex64 directory. What am I 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 protect myself from the comments I made in an endless loop: Matlab should have known there was a compiled version of the function. I don't know how he does it, and my problem is related to this, as several times he finds the function multiple times when he doesn't.

Here is a consolidated online mex sample that does the same "infinity" and runs smoothly:

2D interpolation

Its 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

      

It is possible that .m and .mex64 should be in the same folder.

+3


source to share


1 answer


It all comes down to the Matlab search path . Mex files take precedence over m files if they are at 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 becomes clear that the m file is higher in the search path than in the mex file.



Basically, it's okay if the two files are in the same folder.

+2


source







All Articles