Search code examples
matlabplotmatlab-figure

How can I create a slice of a surface plot to create a line? (Matlab)


Given some function z = f(x,y), I'm interested in creating a (1D) line plot along an arbitrary cutting plane in x,y,z. How do I do this in Matlab? Slice, for example, provides a higher dimensional version (colormap of density data) but this is not what I'm looking for.

E.g.:

z = peaks(50);
surf(z);
%->plot z along some defined plane in x,y,z...

This has been asked before, e.g. here, but this is the answer given is for reducing 3D data to 2D data, and there is no obvious answer on googling. Thanks.


Solution

  • If the normal vector of the plane you want to slice your surface will always lay in the xy plane, then you can interpolate the data over your surface along the x,y coordinates that are in the slicing line, for example, let the plane be defined as going from the point (0,15) to the point (50,35)

    enter image description here

    % Create Data
    z=peaks(50);
    
    % Create x,y coordinates of the data
    [x,y]=meshgrid(1:50);
    
    % Plot Data and the slicing plane 
    surf(z);
    hold on
    patch([0,0,50,50],[15,15,35,35],[10,-10,-10,10],'w','FaceAlpha',0.7);
    
    % Plot an arbitrary origin axis for the slicing plane, this will be relevant later
    plot3([0,0],[15,15],[-10,10],'r','linewidth',3);
    

    Since it is a plane, is relatively easy to obtain the x,y coordinates alogn the slicing plane with linspace, I'll get 100 points, and then interpolate those 100 points into the original data.

    % Create x and y over the slicing plane
    xq=linspace(0,50,100);
    yq=linspace(15,35,100);
    
    % Interpolate over the surface
    zq=interp2(x,y,z,xq,yq); 
    

    Now that we have the values of z, we need against what to plot them against, that's where you need to define an arbitrary origin axis for your splicing plane, I defined mine at (0,15) for convenience sake, then calculate the distance of every x,y pair to this axis, and then we can plot the obtained z against this distance.

    dq=sqrt((xq-0).^2 + (yq-15).^2);
    
    plot(dq,zq)
    
    axis([min(dq),max(dq),-10,10]) % to mantain a good perspective
    

    enter image description here