If you are willing to use undocumented functions, consider the following:
function isValid = checkValidMFile(file_name)
% make sure file can be found
fname = which(file_name);
assert(~isempty(fname) && exist(fname,'file')~=0, 'file not found');
% parse M-file and validate
t = mtree(fname, '-file');
if count(t) == 0 || (count(t)==1 && iskind(t,'ERR'))
isValid = false;
else
isValid = true;
end
end
(You could also pass it a string of MATLAB language code instead of a saved file name).
Of course mtree
will give a lot more information, it can actually return the parse tree, as well as any warnings or errors. I have previously used it to differentiate between scripts vs. functions, and to strip all comments from an M-file.
It is unfortunately not officially supported, so you will have to browse its source code to figure out what everything means (thankfully it is well commented). The function uses the internal mtreemex
MEX-function.
Additional (undocumented) ways:
builtin('_mcheck', 'some_file.m')
and
checkSyntacticWarnings('./path/to/folder/')