npisinp
npisinp

Reputation: 370

How to color a matrix?

I have a matrix in matlab of the following form:

A=[1 1 1 -1 -1
   0 1 0  1  0
   0 1 1  1  1 
   2 2 0  1  2
   2 2 2  2 -1]

This matrix represents a map in the plane. Every A(i, j) is a cell in this map. I want to give color to each cell according to its number. So:

If(A(i, j)<=0)
   color(A(i, j)) with black    
Elseif(A(i, j)==k)
   color(A(i, j)) with color k other than black
end

How to do this in matlab? Any suggestions please?

Upvotes: 0

Views: 178

Answers (1)

NKN
NKN

Reputation: 6414

You can define a number of colours that you want using hsv or manually.

 hsv(3)

ans =

     1     0     0
     0     1     0
     0     0     1

Then use colormap to specify the color map.

colormap(hsv(3))

and then use imagesc

imagesc(A)

enter image description here

If you want to specify the colour also it is easy:

a = hsv(3)
a(1,:) = 1;   % make the first color white
a(3,:) = 0;   % make the last color black

a =

     1     1     1
     0     1     0
     0     0     0

colormap(a)
imagesc(A)

enter image description here

Upvotes: 3

Related Questions