I like the other answers, especially the one by @Amro. But it looks so complicated :) And your caxis
parameters don't need to depend on your input, you can simply grab them from the axis. All this can be a one-liner:
a = gca; % or whatever you use to access your axis handle
a.CLim = max(abs(a.CLim)) * [-1 1];
That's it. This works in MATLAB R2014b onwards, which has the new figure handle system (see more details here). In earlier versions (and new ones, if you prefer), you would use
a = gca; % or whatever you use to access your axis handle
set(a, 'CLim', max(abs(get(a, 'CLim'))) * [-1 1]);
or, using caxis
,
a = gca; % or whatever you use to access your axis handle
caxis(a, max(abs(caxis(a))) * [-1 1]);
Automating this is fairly easy as well:
a = gca; % or whatever you use to access your axis handle
addlistener(a, 'CLimMode', 'PostSet', @(h, e) caxis(e.AffectedObject, max(abs(caxis(e.AffectedObject))) * [-1 1]));
This allows you to do this
for ii = -5 : 5
imagesc([-1 0 10^ii]);
pause(0.2);
end
and the middle stripe (representing 0) is always the middle color of the colorbar.