MATLAB: How to set or get the units block parameter of a Simscape block programmatically through the MATLAB command line

Simscape

I am working with a Simscape model in MATLAB R2018a, and I am trying to modify Simscape block parameters programmatically through the MATLAB command line.
How can I set or get the units property of a Simscape block?

Best Answer

To best explain how to do this, we can demonstrate the method by using one of the shipped Mass-Spring-Damper example models. First, open the example Simscape model by executing the following in MATLAB:
>> ssc_mass_spring_damper_control
Simscape blocks can have numerous parameters that are different for each block. For this reason, it can be helpful to first query the block in question for a list of all the accessible parameters. You can use the 'DialogParameters' property with "get_param" to obtain this list. In the model, click on the "Spring" block to select it, and execute the following command:
>> get_param(gcb, 'DialogParameters')
This should print a list of the dialog parameters of the selected block. An alternative to this would be to use the 'ObjectParameters' property, which returns a full list of the blocks visible and non-visible parameters.
For example, say we wanted to determine the units of the spring constant in this block. If you double-click on the block, we see that it is named "Spring rate" in the block parameters dialog. The name of this parameter in the 'DialogParameters' list is not exactly the same, however there are elements of this list named "spr_rate", "spr_rate_unit", and so on. You can execute the following to obtain the current unit setting:
>> get_param(gcb, 'spr_rate_unit')
This should return 'N/m' for the units. For example, to change the units to 'lbf/ft', execute the following:
>> set_param(gcb, 'spr_rate_unit', 'lbf/ft')
The convention for most Simscape blocks is typically "<variable>_unit" so this may be different depending on the specific block being used.