Search code examples
matlabmatlab-figure

Set color to z-values based on the z-values


I have a surface that I would like to color. The z-values are taken from a 100x100 matrix that range from -10 to 2, and I want something along the lines of

If z is between -10 and -9, color [1 0 0]
If z is between -9 and -8, color [.9 0 0]
....
If z is between -1 and 0, color [.1 0 0]
If z is between 0 and 1, color [0 0 .5]
If z is between 1 and 2, color [0 0 1]

Now, I want to use the same exact color map on a different surface plot. Again, these new z-values are taken from a 100x100 matrix, but its values only range from -5 to 1. So, I want

If z is between -5 and -4, color [.5 0 0]
If z is between -4 and -3, color [.4 0 0]
....
If z is between -1 and 0, color [.1 0 0]
If z is between 0 and 1, color [0 0 .5]

Is there any way to achieve this without manually defining a new color map every time I have a new surface that I want to color?


Solution

  • Since I can't understand the underlying pattern of your color map (and thus translating it into a for loop that automatically calculates the current color based on the data range being currently processed), I would suggest this:

    z_1 = randi([-10 2],100);
    cmap_1 = cell(size(z_1));
    cmap_1(z_1 < -9) = {[1.0 0.0 0.0]};
    cmap_1(z_1 >= -9 & z_1 < -8) = {[0.9 0.0 0.0]};
    % ...
    cmap_1(z_1 >= -1 & z_1 < 0) = {[0.1 0.0 0.0]};
    cmap_1(z_1 >= 0 & z_1 < 1) = {[0.0 0.0 0.5]};
    cmap_1(z_1 >= 2) = {[0.0 0.0 1.0]};
    
    z_2 = randi([-5 1],100);
    cmap_2 = cell(size(z_2));
    cmap_2(z_2 < -4) = {[0.5 0.0 0.0]};
    cmap_2(z_2 >= -4 & z_2 < -3) = {[0.4 0.0 0.0]};
    % ...
    cmap_2(z_2 >= -1 & z_2 < 0) = {[0.1 0.0 0.0]};
    cmap_2(z_2 >= 0) = {[0.0 0.0 0.5]};
    

    To retrieve a value and its respective color:

    my_z = z_1(2,19);
    my_col = cmap_1{2,10};