MATLAB: How to include the model created using TreeBagger in a user-defined function to predict responses using the model

callfunctionincludemodelStatistics and Machine Learning Toolboxtreebagger

How to include the model created using TreeBagger in a user-defined function to predict responses using the model?
I have used TreeBagger to create a random forest model called "Mdl". Now, I want to include "Mdl" in a separate user-defined function.
The function takes some input, "inputX" and performs a predict(Mdl,inputX).
The result from "predict" is the output for the function.
How can the function call the "Mdl"?

Best Answer

To include the model, "Mdl", in the function that you are interested in, you can use any of the following solutions:
1. You can pass the model as an input argument to the function. For example, if you would like to pass the model to the function, "foo", you can define the function to have the model as an input argument, along with any other inputs, like:
function output = foo( Mdl, inputX )
output = predict(Mdl,inputX);
end
Now, you can call this function from the script or the function that creates a random forest model called "Mdl" using the TreeBagger class, as follows:
>> result = foo( Mdl, inputX);
Where, "inputX" is the predictor input that you would like to predict the responses for. Please ensure that the defined function, "foo", is on the MATLAB path. 
2. You can save the created random forest model, "Mdl", in a MAT-file by executing the following command in the Command Window:
>> save('model.mat','Mdl');
Then, you can load the MAT-file in the function that you are interested in, by including the following command in the function definition:
>> load model.mat
Please ensure that the saved MAT-file (model.mat) is on the MATLAB path.