MATLAB: I get an error when I want to generate code for a function that uses CompactModelLoad

Statistics and Machine Learning Toolbox

I want to generate code using MATLAB Coder for a simple GP model as such:
function [Mean] = CmpcPredict(X,ID)
GP_ID = ID;
GP_CmpMdl = loadCompactModel(GP_ID); %this does not compile
% GP_CmpMdl = loadCompactModel('16122391'); %this does compile
[Mean] = predict(GP_CmpMdl,X);
end
It seems like if the ID is specified within the CmpcPredict function, the code generation is completed correctly.
However, if the ID is specified outside of the CmpcPredict function, the code generation returns the following error:
??? Non-constant expression or empty matrix. This expression must be constant
because its value determines the size or class of some expression.

Best Answer

The workflow you have in the example is not supported because the loadCompactModel actually loads the model at compile time, and the predict function is defined for the specific model. As a result, switching the model after code generation is not supported. The running assumption for code generation is that you found a model you are satisfied with, and then you generate code for that specific model.
If you have a set of models that you are choosing according to some criteria, please consider loading all models first and create switch cases for them after that. For example:
CmpMdl1=loadCompactModel('1');
CmpMdl2=loadCompactModel('2');
CmpMdl3=loadCompactModel('3');
switch CASE_ID
case 1
[predict_mean] = preditct(CmpMdl1, X_input);
case 2
[predict_mean] = preditct(CmpMdl2, X_input);
case 3
[predict_mean] = preditct(CmpMdl3, X_input);
end