Real Technology Tools

Simulink: Link a Library Block Programmatically from MATLAB

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 library

The subsystem contains the following blocks: 

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

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.

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.

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:

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

 

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

Exit mobile version