0

I want to convert any number 0<=f<=1 to a rbg code given by four categories green, yellow, orange and red. I can achieve that with the following function:

function [rgb,myColor]=colorCode(f)
cm = [0 1 0;1 1 0;255/255 153/255 51/255;1 0 0];
colorID = max(1, sum(f > [0:1/length(cm(:,1)):1])); 
myColor = cm(colorID, :);
rgb = uint8(myColor*255+0.5);

Now, I will like to do 2 improvements to this:

1.- Above code will divide the interval [0,1] in four equal parts, that is:

[0,0.25]>green
[0.25,0.5]>yellow
[0.5,0.75]>orange
[0.75,1]>red

But I will like to define custom intervals, for instance:

[0,0.3]>green
[0.3,0.5]>yellow
[0.5,0.7]>orange
[0.7,1]>red

2.- I would like that the transition between color intervals to be more smooth. Right now, between 0.25 and 0.26 color changes suddenly from green to yellow. The idea would be to go from green to green-yellow-ish to yellow-green-ish to yellow, and the analogous for the other transitions. I now I have to add more rows to the cm colormap matrix, but I have no idea how....

SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
kurokirasama
  • 737
  • 8
  • 31
  • Possibly related: [Control colorbar scale in MATLAB](https://stackoverflow.com/q/54675647/8239061) which also links to very related posts. – SecretAgentMan Mar 28 '19 at 20:59
  • You can create a custom colormap using [this answer](https://stackoverflow.com/a/54676842/8239061) (see the **Bonus** section) with the [`interp1`](https://www.mathworks.com/help/matlab/ref/interp1.html) function. I realize this isn't a complete answer to your question. – SecretAgentMan Mar 28 '19 at 21:02
  • 1
    Possible duplicate of [How to create a custom colormap programmatically?](https://stackoverflow.com/questions/17230837/how-to-create-a-custom-colormap-programmatically) – SecretAgentMan Mar 28 '19 at 21:05
  • on the off chance this is just a one-off effort and you don't want to do it programmatically, you can try [this](http://www.ece.northwestern.edu/local-apps/matlabhelp/techdoc/ref/colormapeditor.html) – a11 Mar 29 '19 at 02:11
  • 1
    Thanks, between your comments I could make it to work. I'll post the solution – kurokirasama Mar 29 '19 at 13:59

1 Answers1

1
function [rgb,myColor]=colorCode(f)
n=length(f);
switch n
    case 1
        cm = [0 1 0;1 1 0;255/255 128/255 0/255;1 0 0;1 0 0];
        x=[0 0.3 0.5 0.7 1];
        cm = interp1(x,cm, linspace(0, 1, 255));
        colorID = max(1, sum(f > [0:1/length(cm(:,1)):1])); 
        myColor = cm(colorID, :); % returns your color
        rgb = uint8(myColor*255+0.5);
    otherwise
        rgb=zeros(n,3);
        myColor=rgb;
        for i=1:n
            [rgb(i,:),myColor(i,:)]=colorCode(f(i));
        end
end
kurokirasama
  • 737
  • 8
  • 31