MATLAB: How can the “State name” parameter of discrete blocks be set using a variable

simulink

How can the "State name" parameter of discrete blocks be set using a variable?
I would like to use a variable to provide the "State name" for discrete blocks such as the discrete-time integrator block. However, the "State name" for discrete blocks must be specified without quotes and thus cannot accept a variable. In contrast, continuous blocks such as the integrator block require the "State name" to be specified using quotes, which is the desired behavior.
For example, consider that varName = 'Charlie';
Discrete Block Parameter > Resulting state name after code generation
1) varName > varName
2) 'varName' > Error stating that ''varName'' is not allowed
Continuous Block Parameter > Resulting state name after code generation
3) varName > Charlie
4) 'varName' > varName
I need to be able to use the behavior of line #3 for discrete blocks. I want to have discrete blocks within a masked subsystem and enable the user to pick the names of states in code generation from the mask. This requires the ability to set a variable in the mask and use that variable in the individual discrete blocks.

Best Answer

1. Add the following code in the callback function Discrete Block -> Block Properties -> Callbacks tab -> InitFcn
set_param(gcb,'StateName',eval(['myVariable']))
2. Initialize myVariable with char type data in the workspace with the name you wish to have in your generated code. For example:
>> myVariable = 'myStateName';