After reading this article, you’ll be able to lock a library from MATLAB.

We will start with the Simulink model named “mySimpleModel.slx,” including a subsystem linked to a library named “myPersonalLibrary.slx” (if you don’t know how to create a library block from the browser, click here): 

subsystem linked to a librarycustom library block

The subsystem contains the following blocks: 

locked library block

Let’s open the subsystem and modify a block position inside (if you don’t know how to modify a library block, click here):

library block modification

Now, let’s select “Subsystem” and run the following script:

libraryPath = gcb;
set_param(libraryPath, 'LinkStatus', 'propagate');

This will open the library linked to the block you selected.

library of the selected block

Then, you need to save this library before closing it, otherwise, the changes you made in the block won’t be saved. That’s why the complete piece of code is the following:

libraryPath = gcb;
set_param(libraryPath, 'LinkStatus', 'propagate');
 
% save and close the library
libraryBlockHandle = get_param(libraryPath, 'Handle');
block = get(libraryBlockHandle);
libraryName = bdroot(block.ReferenceBlock);
save_system(libraryName);
close_system(libraryName);

If you don’t understand what the code above is doing, refer to the article: Get the Properties of a Simulink Block.

  • In the example, the “ReferenceBlock” field of a block is the location of this block in its library.
  • The bdroot MATLAB command is giving the name of the highest level of the input path argument, namely “myPersonalLibrary”:

bdroot command

This is what we want to save and close.

To recap, in order to lock the library with the desired modifications: 

  1. Take the block “Subsystem” inside “myPersonalLibrary.slx”
  2. Click on “Subsystem”
  3. Run the full script

The result should be the following:

model with locked library block

If you go inside “Subsystem,” you get the following:

locked library block

 

Key takeaways:

  1. To lock a custom library block from MATLAB use:

    set_param(libraryPath, 'LinkStatus', 'propagate');
  2. This will open the corresponding library, get its name using:
    libraryBlockHandle = get_param(libraryPath, 'Handle');
    block = get(libraryBlockHandle);
    libraryName = bdroot(block.ReferenceBlock);
  3. Using the name of this library, save it and close it:
    save_system(libraryName);
    close_system(libraryName);

You can also see the MathWorks documentation about this topic:
https://www.mathworks.com/help/simulink/ug/control-linked-block-status-programmatically.html