Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 683
Samil Avatar asked Jan 13 '11 08:01

Samil


People also ask

How do you find variables in Simulink?

Search for variables within the Model Explorer. Right-click a variable in Model Explorer and select "Find where used". Right-click any Simulink model or block and select "Find referenced variables".


1 Answers

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 alt text, and then select Reports > Code Analyzer Report.

alt text

This will open a new window displaying the MLINT results for each m-file in the current directory:

alt text

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.

like image 166
gnovice Avatar answered Oct 01 '22 00:10

gnovice