Automate Simulink Project Tasks Using Scripts

This example shows how to use the project API to automate project tasks manipulating files, including working with modified files, dependencies, shortcuts, and labels.

Get Project at the Command Line

Open the Airframe project and use currentProject to get a project object to manipulate the project at the command line.

sldemo_slproject_airframe
proj = currentProject
Building with 'MinGW64 Compiler (C)'.
MEX completed successfully.

proj = 

  Project with properties:

                        Name: "Airframe Example"
    SourceControlIntegration: "Git"
          RepositoryLocation: "C:\workSpace\examples\repositories\airframe"
       SourceControlMessages: [1×3 string]
                    ReadOnly: 0
                    TopLevel: 1
                Dependencies: [1×1 digraph]
                  Categories: [1×1 matlab.project.Category]
                       Files: [1×31 matlab.project.ProjectFile]
                   Shortcuts: [1×7 matlab.project.Shortcut]
                 ProjectPath: [1×7 matlab.project.PathFolder]
           ProjectReferences: [1×0 matlab.project.ProjectReference]
                StartupFiles: [1×0 string]
               ShutdownFiles: [1×0 string]
                 Description: "This is an example project.↵↵Use the "Project Shortcuts" toolstrip tab to find ways of getting started with this project."
                  RootFolder: "C:\workSpace\examples\airframe"
         SimulinkCacheFolder: "C:\workSpace\examples\airframe\work\cache"
        ProjectStartupFolder: "C:\workSpace\examples\airframe"
       SimulinkCodeGenFolder: "C:\workSpace\examples\airframe\work\codegen"

Find Project Commands

Find out what you can do with your project.

methods(proj)
Methods for class matlab.project.Project:

addFile                       listModifiedFiles             
addFolderIncludingChildFiles  listRequiredFiles             
addPath                       refreshSourceControl          
addReference                  reload                        
addShortcut                   removeCategory                
addShutdownFile               removeFile                    
addStartupFile                removePath                    
addprop                       removeReference               
close                         removeShortcut                
createCategory                removeShutdownFile            
export                        removeStartupFile             
findCategory                  updateDependencies            
findFile                      
isLoaded                      

Call "methods('handle')" for methods of matlab.project.Project inherited from handle.

Examine Project Files

After you get a project object, you can examine project properties such as files.

files = proj.Files
files = 

  1×31 ProjectFile array with properties:

    Path
    Labels
    Revision
    SourceControlStatus

Use indexing to access files in this list. The following command gets file number 10. Each file has properties describing its path and attached labels.

proj.Files(10)
ans = 

  ProjectFile with properties:

                   Path: "C:\workSpace\examples\airframe\data\system_model.sldd"
                 Labels: [1×1 matlab.project.Label]
               Revision: ""
    SourceControlStatus: Unmodified

Examine the labels of the 10th file.

proj.Files(10).Labels
ans = 

  Label with properties:

            File: "C:\workSpace\examples\airframe\data\system_model.sldd"
        DataType: 'none'
            Data: []
            Name: "Design"
    CategoryName: "Classification"

Get a particular file by name.

myfile = findFile(proj, 'models/AnalogControl.slx')
myfile = 

  ProjectFile with properties:

                   Path: "C:\workSpace\examples\airframe\models\AnalogControl.slx"
                 Labels: [1×1 matlab.project.Label]
               Revision: ""
    SourceControlStatus: Unmodified

Find out what you can do with the file.

methods(myfile)
Methods for class matlab.project.ProjectFile:

addLabel     findLabel    removeLabel  

Get Modified Files

Modify a project model file by adding an arbitrary block.

open_system('AnalogControl')
add_block('built-in/SubSystem', 'AnalogControl/test')
save_system('AnalogControl')

Get all the modified files in the project. Observe two modified files. Compare with the Modified Files view in Project, where you can see a modified model file, and the corresponding project definition file.

modifiedfiles = listModifiedFiles(proj)
modifiedfiles = 

  1×2 ProjectFile array with properties:

    Path
    Labels
    Revision
    SourceControlStatus

Get the second modified file. Observe the file SourceControlStatus property is Modified. Similarly, listModifiedFiles returns any files that are added, conflicted, deleted, etc., that show up in the Modified Files view in Project.

modifiedfiles(2)
ans = 

  ProjectFile with properties:

                   Path: "C:\workSpace\examples\airframe\resources\project\uuid-690c4c18-ad11-4b55-af18-a925aee17dd8.xml"
               Revision: ""
    SourceControlStatus: Added

Refresh source control status before querying individual files. You do not need to do before using listModifiedFiles .

refreshSourceControl(proj)

Get all the project files with a particular source control status. For example, get the files that are Unmodified .

proj.Files(ismember([proj.Files.SourceControlStatus], matlab.sourcecontrol.Status.Unmodified))
ans = 

  1×22 ProjectFile array with properties:

    Path
    Labels
    Revision
    SourceControlStatus

Get File Dependencies

Update the file dependencies. The project runs a dependency analysis to update the known dependencies between project files.

updateDependencies(proj)

Get the list of dependencies in the Airframe project. The Dependencies property contains the graph of dependencies between project files, stored as a MATLAB digraph object.

g = proj.Dependencies
g = 

  digraph with properties:

    Edges: [21×1 table]
    Nodes: [21×1 table]

Get the files required by a model.

requiredFiles = bfsearch(g, which('AnalogControl'))
requiredFiles =

  3×1 cell array

    {'C:\workSpace\examples\airframe\models\AnalogControl.slx'}
    {'C:\workSpace\examples\airframe\data\controller.sldd'    }
    {'C:\workSpace\examples\airframe\data\buses.sldd'         }

Get the top-level files of all types in the graph.

g.Nodes.Name(indegree(g)==0);

Get the top-level files that have dependencies.

g.Nodes.Name(indegree(g)==0 & outdegree(g)>0)
ans =

  4×1 cell array

    {'C:\workSpace\examples\airframe\models\DigitalControl.slx'}
    {'C:\workSpace\examples\airframe\models\LinearActuator.slx'}
    {'C:\workSpace\examples\airframe\models\slproject_f14.slx' }
    {'C:\workSpace\examples\airframe\tests\f14_airframe_test.m'}

Find impacted (or "upstream") files by creating a transposed graph.

transposed   = flipedge(g)
impacted = bfsearch(transposed, which('vertical_channel'))
transposed = 

  digraph with properties:

    Edges: [21×1 table]
    Nodes: [21×1 table]


impacted =

  4×1 cell array

    {'C:\workSpace\examples\airframe\models\vertical_channel.slx'}
    {'C:\workSpace\examples\airframe\models\f14_airframe.slx'    }
    {'C:\workSpace\examples\airframe\models\slproject_f14.slx'   }
    {'C:\workSpace\examples\airframe\tests\f14_airframe_test.m'  }

Find files impacted by a data dictionary.

impacted2 = bfsearch(transposed, which('buses.sldd'))
impacted2 =

  11×1 cell array

    {'C:\workSpace\examples\airframe\data\buses.sldd'             }
    {'C:\workSpace\examples\airframe\data\controller.sldd'        }
    {'C:\workSpace\examples\airframe\data\system_model.sldd'      }
    {'C:\workSpace\examples\airframe\tests\f14_airframe_test.m'   }
    {'C:\workSpace\examples\airframe\models\AnalogControl.slx'    }
    {'C:\workSpace\examples\airframe\models\DigitalControl.slx'   }
    {'C:\workSpace\examples\airframe\models\f14_airframe.slx'     }
    {'C:\workSpace\examples\airframe\models\LinearActuator.slx'   }
    {'C:\workSpace\examples\airframe\models\NonLinearActuator.slx'}
    {'C:\workSpace\examples\airframe\models\slproject_f14.slx'    }
    {'C:\workSpace\examples\airframe\models\vertical_channel.slx' }

Get information on your files, such as the number of dependencies and orphans.

averageNumDependencies = mean(outdegree(g));
numberOfOrphans = sum(indegree(g)+outdegree(g)==0);

If you want to make changes to a model hierarchy, starting from the bottom up, find the topological order.

ordered = g.Nodes.Name(flip(toposort(g)));

Query Shortcuts

Examine the project's Shortcuts property.

shortcuts = proj.Shortcuts
shortcuts = 

  1×7 Shortcut array with properties:

    Name
    Group
    File

Examine a shortcut in the array.

shortcuts(7)
% Get the file path of a shortcut.
shortcuts(7).File
ans = 

  Shortcut with properties:

     Name: "Rebuild Project's S-functions"
    Group: "Utility"
     File: "C:\workSpace\examples\airframe\utilities\rebuild_s_functions.m"


ans = 

    "C:\workSpace\examples\airframe\utilities\rebuild_s_functions.m"

Examine all the files in the shortcuts cell array.

{shortcuts.File}'
ans =

  7×1 cell array

    {["C:\workSpace\examples\airframe\custom_tasks\analyzeModelFiles.m"]}
    {["C:\workSpace\examples\airframe\custom_tasks\billOfMaterials.m"  ]}
    {["C:\workSpace\examples\airframe\custom_tasks\checkCodeProblems.m"]}
    {["C:\workSpace\examples\airframe\custom_tasks\runUnitTest.m"      ]}
    {["C:\workSpace\examples\airframe\models\slproject_f14.slx"        ]}
    {["C:\workSpace\examples\airframe\reports\slproject_f14.pdf"       ]}
    {["C:\workSpace\examples\airframe\utilities\rebuild_s_functions.m" ]}

Label files

Create a new category of labels, of type char. In the Project, the new Engineers category appears in the Labels pane.

createCategory(proj, 'Engineers', 'char')
ans = 

  Category with properties:

                Name: "Engineers"
        SingleValued: 0
            DataType: "char"
    LabelDefinitions: [1×0 matlab.project.LabelDefinition]

Find out what you can do with the new category.

category = findCategory(proj, 'Engineers');
methods(category)
Methods for class matlab.project.Category:

createLabel  findLabel    removeLabel  

Define a new label in the new category.

createLabel(category, 'Bob');

Get a label definition.

ld = findLabel(category, 'Bob')
ld = 

  LabelDefinition with properties:

            Name: "Bob"
    CategoryName: "Engineers"

Attach a label to the retrieved file, myfile. If you select the file in Project, you can see this label in the label editor pane.

addLabel(myfile, 'Engineers', 'Bob');

Get a particular label and attach data to it, for example, some text.

label = findLabel(myfile, 'Engineers', 'Bob');
label.Data = 'Please assess'
label = 

  Label with properties:

            File: "C:\workSpace\examples\airframe\models\AnalogControl.slx"
        DataType: 'char'
            Data: 'Please assess'
            Name: "Bob"
    CategoryName: "Engineers"

You can specify a variable for the label data, for example:

mydata = label.Data
mydata =

    'Please assess'

Create a new label category with numeric data type.

createCategory(proj, 'Assessors', 'double');
category = findCategory(proj, 'Assessors');
createLabel(category, 'Sam');

Attach the new label to a specified file and assign data value 2 to the label.

myfile = proj.Files(14);
addLabel(myfile, 'Assessors', 'Sam', 2)
ans = 

  Label with properties:

            File: "C:\workSpace\examples\airframe\models"
        DataType: 'double'
            Data: 2
            Name: "Sam"
    CategoryName: "Assessors"

Close Project

Closing the project at the command line is the same as closing the project using the Project tool. For example, the project runs shutdown scripts ad checks for unsaved models.

close(proj)

More Information

For more details on using the API, enter: doc currentProject.

To automate start and shutdown tasks, see Automate Startup Tasks.

See Also

| | | |

Related Topics