Update
Temporarily removing and adding a parameter to the mask is not trivial either, the following code should in theory accomplish the task
function SetBlockParameterToMaskedVariable(modelName, block, blockParam, varName)
% Assumes the model is a loaded subsystem, block belongs to the subsystem and has a parameter blockParam.
maskObj = Simulink.Mask.get(modelName);
% If there is no mask or the mask does not have the parameter, just set the block parameter
if isempty(maskObj) || isempty({maskObj.getParameter(varName).Name})
set_param(block, blockParam, varName);
return;
end
% Copy the mask parameter settings and remove the parameter from the mask
maskParameter = maskObj.getParameter(varName);
maskParameterCopy = GetMaskParamCopy(maskParameter);
maskObj.removeParameter(varName);
% Set the block parameter to reference the mask variable
set_param(block, blockParam, varName);
% Re-add the mask parameter to the mask
maskObj.addParameter('Type', maskParameterCopy.Type, ...
'Name', maskParameterCopy.Name, ...
'Prompt', maskParameterCopy.Prompt, ...
'Value', maskParameterCopy.Value, ...
'Evaluate', maskParameterCopy.Evaluate, ...
'Tunable', maskParameterCopy.Tunable);
end
function paramCopy = GetMaskParamCopy(maskParameter)
% Returns a struct with the properties of the mask parameter
paramCopy = struct();
paramCopy.Type = maskParameter.Type;
paramCopy.Name = maskParameter.Name;
paramCopy.Prompt = maskParameter.Prompt;
paramCopy.Value = maskParameter.Value;
paramCopy.Evaluate = maskParameter.Evaluate;
paramCopy.Tunable = maskParameter.Tunable;
end
However, the exact same error is encountered despite the mask parameter having been removed. The only way I could make this work was by saving the model just before set_param, closing it and then loading it again. I was then able to set the block parameter. This is not a viable solution though, first because it is slow, and second because it requires reinitialization of all model references that were invalidated when we closed the model.
My assumption is that the mask workspace is only evaluated when loading the model, and thus it tries to infer the value of 'MyParam' even though it has been removed from the model's mask.
-> Is there any way to make matlab re-evaluate the mask workspace without closing and loading the model?