Find unused variables and functions in a MATLAB-Simulink project
I have a complex MATLAB-Simulink project involving many m-files and mdl-files. Some m-files define variables that are used in other m-files (bad design, I know, but it is legacy code). There are also functions that aren't used anymore.
I need an automatic way to find unused variables and functions so that I can delete them and make the whole thing a little less complex. Ideally I should have a script/tool which takes as input the name of root directory of the project, scans all the files in subdirectories, and outputs all the variables and functions that are not used in any m-file or mdl-file.
I know that I can find variables that are not used in mdl-files (see Tips and Tricks - Tracking Variables in a Simulink Model). I would like to apply开发者_如何学运维 that method to all the files in the project.
My idea to detect variables not used in m-files is to temporarily combine all the m-files into a single file and run mlint on it. Any better ideas?
Instead of going through the tedious (and potentially error-prone) task of pasting all of your m-files into one to run MLINT, you have a few other options...
If you have all your files in one folder, the simplest approach is to go to the Current Folder browser, click the Actions button
, and then select Reports > Code Analyzer Report.This will open a new window displaying the MLINT results for each m-file in the current directory:
If you would rather automate the process using a script instead of having to click through menu options, there are a couple of submissions on the MathWorks File Exchange (here and here) that appear to work recursively on a directory structure as opposed to just a single directory.
In additional, here is some sample code that will do what you want for a single directory:
dirData = dir; %# Get data on the current directory contents
fileIndex = ~[dirData.isdir]; %# Get an index for the files
fileNames = {dirData(fileIndex).name}; %# Get the file names
[~,~,ext] = cellfun(@fileparts,fileNames,... %# Get the file extensions
'UniformOutput',false);
mFileIndex = strcmp(ext,'.m'); %# Get an index for the m-files
cellfun(@mlint,fileNames(mFileIndex)); %# Run MLINT on each m-file
You could extend the collection of file names (and paths) in this way to operate recursively on a directory tree, then run MLINT on the resulting set of files you collect.
精彩评论