MATLAB: Display data in matrix with two different colour scales, depending on cell value

3d plotscolorcolormapfigureimageMATLABplotplotting

Hi
I have a 20×20 matrix and want to display it as an image. In this image I want to be able to represent two properties of each cell: its value and wether or not this value is above a certain threshold (0.1).
I was thinking about this: to represent cells with a value lower than 0.1 by a green colour. The shade of green must be darker for a lower value and lighter for a higher value (closer to 0.1). If the value is larger than 0.1, it must be represented by a red colour, and its shade must also change from lighter red to darker red (lower => higher).
Is there any way to do this in matlab?
Best regards

Best Answer

  • This first bit of code sets up a colormap with 2*N colors ranging from dark green to light green to light red to dark red:
    N = 100;
    g = [zeros(N,1), linspace(100, 255, N)', zeros(N,1)] ./ 255;
    r = [linspace(255, 100, N)', zeros(N,1), zeros(N,1)] ./ 255;
    c = colormap([g; r]);
    The below section creates a 20x20 matrix with random values between 0 and 1 (A0). Each value in A0 is then mapped to a new value in A which corresponds to its index within the colormap. Values above the cutoff are mapped to values above N (red colors), and values below the cutoff are mapped to values below N (green colors):
    A0 = rand(20,20);
    cutoff = 0.1;
    A = A0;
    Alow = A(A0<cutoff);
    Ahigh = A(A0>cutoff);
    biggerRange = max([range(Alow) range(Ahigh)]);
    A(A0<cutoff) = N - round(N * (Alow - min(Alow)) / biggerRange);
    A(A0>cutoff) = N + round(N * (Ahigh - min(Ahigh)) / biggerRange);
    image(A)
    The above code uses the same scale for both regions of values (above and below the cutoff). A very dark green cell will be the same distance to the cutoff as an equally dark red cell. However, for a cutoff of 0.1, all of the green cells will be very light green because their corresponding values can't be more than 0.1 away from the cutoff. If you'd prefer to scale the green and red values separately, between their respective mins and maxes, you could do so:
    A0 = rand(20,20);
    cutoff = 0.1;
    A = A0;
    Alow = A(A0<cutoff);
    Ahigh = A(A0>cutoff);
    A(A0<cutoff) = round(N * (Alow - min(Alow)) / (max(Alow) - min(Alow)));
    A(A0>cutoff) = N + round(N * (Ahigh - min(Ahigh)) / (max(Ahigh) - min(Ahigh)));
    image(A)
    Here, for a cutoff of 0.1, a very dark green cell is much closer to the cutoff than an equally dark red cell, which could be misleading.
    Hopefully this is helpful!