Using prediction model inside a matlab function block

3 views (last 30 days)
This is the content in the prediction file.
data1new=readtable('processed_data.csv');
X1 = data1new{:,1:end-1};
Y1 = data1new{:,end};
% Train a Random Forest ensemble using all the data
ensnew = fitrensemble(X1,Y1,'Method','bag','NumLearningCycles',150,'Learners','tree');
NH5pred=predict(ensnew,X1);
%saving the model for future use.
save('NH5predModel.mat','ensnew');
The image shows the data being collected and the MUX block delivers the input to the function block.
Inside the matlab function block:
function y = Regpred(inputt)
% Load the regression model
loadedData = load('NH5predModel.mat', 'ensnew');
ensnewLoaded = loadedData.ensnew;
% Ensure input has 8 columns
if size(inputt, 2) ~= 8
error('Input must have 8 columns.');
end
% Preallocate the output variable y based on the size of input
numRows = size(inputt, 1);
y = zeros(numRows, 1); % Assuming a single output value per row of input
% Make predictions using the loaded model
for i = 1:numRows
y(i) = predict(ensnewLoaded, inputt(i, :));
end
The outport the matlab function block is a To workspace block.
The error encountered is also attached. Please help!

Accepted Answer

Drew
Drew on 3 Nov 2023
MathWorks provides Simulink blocks for machine learning model prediction. So, rather than using a generic MATLAB function block for the model prediction, you can use the native Simulink block designed for model prediction for your random forest model. Check the "Blocks" section of the doc page https://www.mathworks.com/help/stats/code-generation.html.
Given that your model is a random forest trained with fitrensemble, the matching Simulink block is the RegressionEnsemble Predict block:
The sidebar indicates that you are using R2020a. Note that this "RegressionEnsemble Predict" block was added in R2021a.
If this answer helps you, please remember to accept the answer.

More Answers (0)

Products


Release

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!