MATLAB: Save CART as fig without displaying

cartfigure

I have created a decision tree for classification using fitctree, tree=fitctree(…). I can visualise it using the command view(tree,'Mode','Graph'). I can then use the option "Save as" from the File menu to save the tree as a .fig file. However, I would like to save the tree as .fig directly without the visualisation step. I have tried: tree=fitctree(…); h = view(tree); saveas(h,'filename','fig'); but it doesn't work. I get the error: Error using ClassificationTree/view Too many output arguments. Any ideas how to save a CART tree as .fig, but without displaying it? I would like to be able to do this from the command window, so using the "Save as" from the file menu is not an option.

Best Answer

Although the handle is not readily available as an output of "view", you can obtain the figure handle using the "findall" command. You can then save as a FIG file using the "saveas" command. Here is an example:
% Load data and make a table
load carsmall
tbl = table(Weight,Cylinders,MPG,Origin);
% Fit Classification Tree
tree = fitctree(tbl,'Origin');
% Call the view function
view(tree,'mode','graph');
% Obtain the handle
h = findall(0,'type','figure','Name','Classification tree viewer');
% Save file
saveas(h,'classTree.fig');
This method would still display the tree, but you would be able to save it from the Command Window.