MATLAB: Figure colorbar is not refreshed

figureMATLAB

I recently updated MATLAB from R2016b to R2019b, and noticed my codes drawing figures do not work in the same way.
When I draw an image with a colorbar and set scaled CDataMapping, the image reflects scaled color scheme but the scales on the colorbar is not refreshed.
How I can make them refreshed every time I update CData of the image?
Below is my example in which colorbar scale is not refreshed.
Thank you,
read = zeros(4, 'uint16');
readcount = 0;
fig = figure;
img = image (read,'CDataMapping','scaled');
c = colorbar;
while 1 == 1
readcount = readcount + 1;
read(mod(readcount,16)+1) = read(mod(readcount,16)+1) + readcount;
img.CData = read;
drawnow;
end

Best Answer

Control the limits of the colorbar using caxis(). This line adjusts the colorbar limits to the range of your data.
caxis([min(read(:)),max(read(:))]);
The reason why caxis('auto') doesn't adjust your colorbar limits in this case is because it only responds when the colormap indexing array changes. To demonstrate this, run this line of code after a few iteration of your currently existing code.
colormap(parula(10))
[Addendum]
You could also use the clim property of the axes
ax = gca();
ax.CLim = [min(read(:)),max(read(:))]