MATLAB: Is there a native function in MATLAB that can determine if a MATLAB file or P-file is a function or script

isfunctionMATLABpcode

I want to know if there is a native function in MATLAB which can determine if a MATLAB file or P-file is a function or script.

Best Answer

The ability to determine if a MATLAB file or P-file (Pcode) is a function or a script is not available in MATLAB 7.3 (R2006b).
As a workaround, you may use the following function to determine if a file is a function:
function result = isfunction(fname)
% Open the file passed as a string to the function
fid = fopen(fname,'rt');
% Make sure the file opened correctly
if (fid < 1)
error(ferror(fid))
end
result = false;
% Count the number of lines
while ~feof(fid) && ~result
str = fgetl(fid);
trimmed_str = strtrim(str);
if ~isempty(trimmed_str) && ~strcmp(trimmed_str(1), '%')
try
result = strcmp(trimmed_str(1:8), 'function');
catch
%first line of code is not a function
break
end
end
end
% Close the file
fclose(fid);
There is no workaround to determine if a P-file is a function.