Search code examples
matlabgraphicsmatlab-figure

Create stacked 2d matrix along z axis with surf in MATLAB


The following figure is just a representation of a 2d array with surf. I would like to create a similar figure with 10 of these 2d arrays stacked on top of each other with some kind of offset along the z axis.

figure();
surf(X);
colormap(hsv);
shading interp;
campos([-70 -150 80]);
grid on;
set(gcf,'color','w');

enter image description here


Solution

  • Just call surf several times with hold on, applying a gradually increasing offset.

    By default (1-input version of surf), the offset will affect the colors shown for each surface. Here's an example with three 2D arrays. Note that peak-to-peak amplitude is different for each one.

    x{1} = .2*peaks(30);
    x{2} = .4*peaks(30);
    x{3} = .8*peaks(30); % cell array containing three 2D arrays
    offset = 7; % desired offset
    hold on
    for k = 1:numel(x)
        surf(x{k} + offset*(k-1))
    end
    campos([-100 -170 90])
    grid on
    

    enter image description here

    To prevent offset from affecting color, i.e. achieve consistent color for all surfaces, use the 2- or 4-input version of surf to separately specify height and color:

    x{1} = .2*peaks(30);
    x{2} = .4*peaks(30);
    x{3} = .8*peaks(30);
    offset = 7;
    hold on
    for k = 1:numel(x)
        surf(x{k} + offset*(k-1), x{k}) % Only this line has been changed
    end
    campos([-100 -170 90])
    grid on
    

    enter image description here

    To generate stacked planes (no height variations) with color depending on value: modify the input arguments as follows:

    x{1} = .2*peaks(30);
    x{2} = .4*peaks(30);
    x{3} = .8*peaks(30);
    offset = 7;
    hold on
    for k = 1:numel(x)
        surf(repmat(offset*(k-1), size(x{k})), x{k}) % Only this line has been changed
    end
    campos([-100 -170 90])
    grid on
    

    enter image description here