I understand that “loadLearnerForCoder” generated code uses runtime “memcpy” to load your SVM model, eating up RAM on Cortex-M targets. You can avoid this in two ways -
1) Use a single MATLAB Coder entry point function to load the SVM Struct and then use predict function. Consider the following dataset (for demonstration purpose only) -
X = [randn(50,2)+1.5; randn(50,2)-1.5];
Y = [ones(50,1); -ones(50,1)];
svmModel = fitcsvm(X, Y, ...
'KernelFunction','rbf', ...
svmModel = compact(svmModel);
saveLearnerForCoder(svmModel, 'svmModelForCoder.mat');
In MATLAB create a “svmPredictEntry” function -
function labels = svmPredictEntry(data)
svmStruct = loadLearnerForCoder('svmModelForCoder.mat', 'DataType','single');
labels = predict(svmStruct, data);
From command line, generate code :
codegen -c svmPredictEntry -args {zeros(1,2,'single')}
In the generated Code, the “supportVectors appear as constants within the function scope, hence eliminating the need to copy data using “memcpy”.
2) Consider wrapping each array in a “Simulink.Parameter” object and set its “customStorageClass” if you can write the predict function using the trained parameters.
Let’s use the same data as above for demonstration,
- Create “Simulink.Parameter” with “Custom” storage class and set to “Const”
alpha = Simulink.Parameter(single(svmModel.Alpha));
alpha.CoderInfo.StorageClass = 'Custom';
alpha.CoderInfo.CustomStorageClass = 'Const';
svT = Simulink.Parameter(single(svmModel.SupportVectors'));
svT.CoderInfo.StorageClass = 'Custom';
svT.CoderInfo.CustomStorageClass = 'Const';
mu = Simulink.Parameter(single(svmModel.Mu));
mu.CoderInfo.StorageClass = 'Custom';
mu.CoderInfo.CustomStorageClass = 'Const';
sigma= Simulink.Parameter(single(svmModel.Sigma));
sigma.CoderInfo.StorageClass = 'Custom';
sigma.CoderInfo.CustomStorageClass = 'Const';
Create a Simulink model with a MATLAB Function block with the following code -
function y = fcn(u, alpha, mu, sigma)
y = alpha(1)*u + mu(1) - sigma(1);
Note that you must set the Scope as “Parameter” for all the inputs in MATLAB Function block. After opening the MATLAB function block, click on “Edit Data”. Then click on “create Data” from “Symbols” window. Also set the correct “size” and “type” for each input.
Finally set the system target file to “ert.tlc” and generate the code for your model. Here’s a snapshot of the generated code with global constants:
Hope this resolves your query!