How To Build Decision Tree in MATLAB? (original) (raw)

Last Updated : 28 Apr, 2025

MATLAB is a numerical and programming computation platform that is primarily used for research, modeling, simulation, and analysis in academics, engineering, physics, finance, and biology. MATLAB, which stands for "MATrix LABoratory," was first trying out typical tasks such as matrices operations, linear algebra, and signal processing

It has additional use in artificial intelligence, deep learning, and machine learning, and it contains a variety of toolboxes for certain applications including control systems, optimization, and image processing.

How to build a decision tree in MATLAB?

Example 1:

Matlab `

% Loading the Iris dataset. load fisheriris

% Splitting the data into training and testing.

cv = cvpartition(species,'HoldOut',0.3); Xtrain = meas(cv.training,:); Ytrain = species(cv.training); Xtest = meas(cv.test,:); Ytest = species(cv.test);

% Training the decision tree model. tree = fitctree(Xtrain, Ytrain);

% Viewing the decision tree. view(tree,'Mode','graph');

% Predicting the classes of the testing set. Ypred = predict(tree, Xtest);

% Calculate the accuracy of the model.

accuracy = sum(Ypred == Ytest)/length(Ytest); disp(['Accuracy: ' num2str(accuracy)]);

`

Output: