MATLAB Answers

0

How can I display elements of a 2D matrix as blue, green and red squares?

Asked by Felipe Higa on 20 Jul 2018
Latest activity Answered by Image Analyst
on 21 Jul 2018
Hi guys!
I have a problem when I try to use a colormap. I have a vector A and a vector B, for each combination of elements from A and B, my matrix C gets a number that can be 0, 5 or 10. So, for example, for A(2) and B(2), C(2,2) is 0. For A(3), B(5), C(3,5) is 10. I'm using mesh to plot my matrix C, then, I change to view(2) and use that new view. Also, I use colormap(jet) so the elements 0 are represented by a blue square. The elements 5 by green and the elements 10 by red. My problem is that when my matrix C has for example only 0 and 5, then I get only blue and red squares. I want to get blue and green in this case. The same happens when my C has only 5 and 10. How can I correct that?
mesh(A,B,C)
map = colormap(jet);
map(1,1) = 0;
map(1,3) = 1;
map(64,1) = 1;
map(64,3) = 0;
colormap(map);
view(2)

  0 Comments

Sign in to comment.

3 Answers

Answer by Kelly Kearney
on 20 Jul 2018
 Accepted Answer

You just need to set the color limits:
set(gca, 'clim', [0 10]);

  1 Comment

Sign in to comment.


Answer by Aquatris
on 20 Jul 2018

A simple fix would be to add 3 additional variables to your matrices that have X and Y values that are outside of your region of interest and Z values that are 0, 5, and 10. This might solve your issue by forcing the color assignment to be the same since Z will always have all three variables.

  2 Comments

Here is an example to play with;
x = 1:4;
y = 1:4;
x = [x 10]; % x = 10 is the dummy
[A,B] = meshgrid(x,y)
C = zeros(4,4);
C(1:2,3:4) = 5;
C(:,5) = [0 5 10 0]'; % dummy C to let C have all 3 variables
mesh(A,B,C)
map = colormap(jet);
map(1,1) = 0;
map(1,3) = 1;
map(64,1) = 1;
map(64,3) = 0;
colormap(map);
view(2)
axis([1 4 1 4]) % region of interest
I was using these additional variables before coming here to ask, but I thought there was another way to do that. Anyway, thanks for your answer.

Sign in to comment.


Answer by Image Analyst
on 21 Jul 2018

You might like to take a look at the heatmap() function or im2html. Not really a solution but kind of related and might be interesting.

  0 Comments

Sign in to comment.