MATLAB: Does the COLORBAR function create a new color bar when I want to only update the existing color bar

horizontallocationmanualMATLABsouthoutsidevertical

When I create an image and a color bar as follow,
hi = imagesc(rand(256, 256));
hc = colorbar('peer', gca,'EastOutside','position',[0.1 0.05 0.02 0.8]);
and then change the range of my data using the command,
set(hi, 'CData', 200*rand(256,256));
and try to update the color bar using the command,
hc = colorbar('peer', gca,'EastOutside','position',[0.1 0.05 0.02 0.8]);
a new color bar is place on top of the old one. I expected the color bar to be updated.

Best Answer

We have verified that there is a bug in MATLAB 7.0.4 (R14SP2) in the way that the COLORBAR function checks for existing color bars with user-defined position vectors.
To work around this issue, save the handle of the color bar you wish to update or replace. When you are ready to update the color bar, delete the color bar and create a new color bar. For example,
hi = imagesc(rand(256, 256));
hc = colorbar('peer', gca,'EastOutside','position',[0.05 0.1 0.015 0.8]);
set(hi, 'CData', 200*rand(256,256));
delete(hc);
hc = colorbar('peer', gca,'EastOutside','position',[0.05 0.1 0.015 0.8]);