MATLAB: Colormap with both positive and negative values

colormapimagesc

Hi all,
I have a very simple issue, but the solution has been escaping me nonetheless.
I have a big matrix of correlations: some are negative and some are positive. I would like to plot them with a red-green colormap (like the "colormap(redgreencmap)" for "imagesc"). In this map, a correlation of -1 should be bright red, a correlation of +1 bright green and a correlation of close to zero black.
However, it seems like MATLAB can only handle matrices of values between [0,1] for colormap plotting.
This should be pretty simple, but I cannot figure out the solution. Does anyone have any suggestions?
Thanks a lot,
Anders

Best Answer

Try this:
% Create sample data:
correlations = peaks(300);
minValue = min(correlations(:));
maxValue = max(correlations(:));
% Scale the data to between -1 and +1.
correlations = (correlations-minValue) * 2 / (maxValue - minValue) - 1;
% Display - will use some weird color map to start with.
imagesc(correlations);
colorbar
% Create colormap that is green for negative, red for positive,
% and a chunk inthe middle that is black.
greenColorMap = [zeros(1, 132), linspace(0, 1, 124)];
redColorMap = [linspace(1, 0, 124), zeros(1, 132)];
colorMap = [redColorMap; greenColorMap; zeros(1, 256)]';
% Apply the colormap.
colormap(colorMap);
Related Question