Search code examples
matlab3ddata-visualizationmatlab-figuresurface

Gradient colors for faces of surface


I have the following code for MATLAB:

close all
clear all
clc
edges= linspace(0,1,10);
[X,Y] = meshgrid(edges);
Z=rand(10);
h= surf(X,Y,Z,'FaceColor','none')

I need to paint the faces on this surface. The face with coordinate (0,0) should be green and the face with coordinate(1,1) should be red. All faces on diagonal should be yellow.

Could You help me to perform this painting?


Solution

  • If you have a closer look at the surf command, you'll see, that you can set a custom "colormap", which is then used instead of the Z data as a color indicator.

    So, you just have to set up a proper "colormap". That one must have the same dimensions as your X and Y data, and for each data point you must specify the [R, G, B] triplet of your choice, i.e. [0, 1, 0] for the [0, 0] coordinate, [1, 0, 0] for the [1, 1] coordinate, and some "diagonal" interpolation between those two.

    Luckily, you already have that, have a look at your X and Y data! Adding both will give that kind of "diagonal" interpolation for the green channel. The inverse of that will give the proper red channel. (The scaling is a bit corrupt, since you have values larger than 1.0, but these will "clipped".)

    Here's the enhanced code:

    edges = linspace(0, 1, 10);
    [X, Y] = meshgrid(edges);
    Z = rand(10);
    cm(:, :, 1) = (X + Y);          % Red channel
    cm(:, :, 2) = 2 - cm(:, :, 1);  % Green channel
    cm(:, :, 3) = zeros(size(X));   % Blue channel (empty)
    h = surf(X, Y, Z, cm);          % No need for the FaceColor property
    

    The output looks like this:

    Output

    Hope that helps!