MATLAB: Does copyobj return an error when Copying Legends or Colorbars in MATLAB R2014b

MATLABr2014bgraphics

Why does copyobj return an error when copying legends or colorbars in MATLAB R2014b?

Best Answer

Starting in MATLAB R2014b, legends and colorbars must be associated with an axes. If you want to copy a legend or a colorbar using copyobj, you also must copy the associated axes.
Copying a legend without the associated axes returns an error message. For example:
plot(rand(2))
l = legend('show'); % legend
ax = gca; % associated axes
fnew = figure; % new figure
copies = copyobj(l,fnew); % copy only legend to new figure
Error using matlab.graphics.illustration.Legend/connectCopyToTree (line 5)
A legend must be copied with its associated axes. Use a vector input with COPYOBJ in order to copy the legend and axes together.
You must copy both the legend and the associated axes.
copies = copyobj([l,ax],fnew)
2x1 graphics array:
Legend (data1, data2)
Axes