Luther_Blissett
Luther_Blissett

Reputation: 327

How to assign specific values to colours in imagesc

I'm trying to assign three possible values of a matrix to three colours when plotted using imagesc in MATLAB.

All I want is imagesc() to represent 0 as white, 1 as black and 2 as red.

Initially imagesc() does this, but as the for-loop proceeds, the colours for 1 and 2 get swapped.

I have tried re-ordering the colours assigned to colormap(), but the colours still swap.

Here is my code:

Grid = 10;
M = zeros(Grid);
M(3,1:3)=1;M(2,3)=1;M(1,2)=1;
Black = [0 0 0];
White = [1 1 1];
Red = [1 0 0];
Background = White;
colormap([Background; Red; Black])
figure()
imagesc(M)

...so far, so good. I have five black squares in the corner.

However as my loop proceeds and 2's are introduced, the matrix looks like this:

0   0   0   0   0   0   0
0   2   1   0   0   0   0
1   0   1   0   0   0   0
0   1   1   0   0   0   0
0   0   0   0   0   0   0
0   0   0   0   0   0   0
0   0   0   0   0   0   0
0   0   0   0   0   0   0
0   0   0   0   0   0   0
0   0   0   0   0   0   0

but now the image shows BLACK for 2, and RED for 1.

How do I maintain the colour-to-value relationships?

Upvotes: 1

Views: 2016

Answers (1)

Dev-iL
Dev-iL

Reputation: 24159

Your main mistake is having the red and black colors reversed in your colormap. You probably did this because putting the colors in the correct order made the pixels red in your first matrix - which was unwanted. The reason for this is the way pixel values are mapped to colormap colors, which can be seen by showing a colorbar. Your custom colormap happened to work because red was used for pixels with a value of about 0.5 - of which there were none.

What you need to do is correctly set the color limits for your axes:

colormap([Background; Black; Red])
set(gca, 'CLim', [0 2]);

Then, this is what would happen for the initial matrix (note that there are no red pixels in the image, but the colormap is ready for them nonetheless):

enter image description here

Upvotes: 3

Related Questions