MATLAB: How to avoid variable (or file) name conflicts when using multiple copies of library subsystems with To Workspace (or To File) blocks

dataduplicateexportloggingmaskingsimulinktofiletoworkspacevariable

I am creating a model and using a subsystem that I created and placed in a custom library. This subsystem has a To Workspace block in it that has the default variable name as 'simout'. Thus this block will save data to a variable named 'simout' in the MATLAB workspace.
The problem is that when I use two copies of this subsystem block, I now face a naming conflict as two blocks are trying to save data to the same variable. In order to change the variable name, I need to break the library link. However, I need to retain the library link as I need to make changes to the subsystem block.
The same issue arises if I have a To File sink block instead of a To Workspace block in my library subsystem.

Best Answer

This conflict can be resolved by creating a mask for the subsystem block in the library itself. The following example demonstrates this.
Suppose that you have a library subsystem block that contains a To Workspace block whose variable name is "simout".
In your library, create a Mask for the subsystem block by right-clicking on the block and selecting 'Mask Subsystem'. Create a mask parameter for the mask and let this be the variable name that the To Workspace block inside will take, e.g.:
Mask Prompt: 'Variable Name'
Variable: simout
Now, click on click on the 'Initialization' tab of the Mask Editor and add the following statement to the initialization commands to set the variable name to the specified name in the mask. Also, check the option 'Allow library block to modify its contents'.
set_param([gcb,'/To Workspace'], 'VariableName', simout)
This will ensure that when the value of this parameter is changed, the above initialization will be executed and it will change the variable name for the To Workspace block within the subsystem accordingly. Note that the library link is intact while this is done.
When you use two or more copies of this library block in your model, you open up the mask dialog for this block and choose the variable name that you would like the To Workspace block to use. As long as you provide different names for all the copies of this subsystem in your mode, the naming conflict is resolved.