matlabplotpolygonmatlab-figuresurface

Plotting a function inside a polygon in MATLAB


Is there a way to plot a given function with the domain restricted to a polygon with given vertices, in MATLAB?

For example, how can I plot the function

f =@(x,y) x.*y

inside the polygon whose vertices are given by p1 = [0 0], p2 = [1 0], p3 = [2 2], p4 = [0 1]?

I know there exists the function inpolygon, but I don't have any idea on how to use it to plot a function only inside the polygon.


Solution

  • You can generate a mesh for x-y points in the bounding box of your polygon, make points outside the polygon equal to NaN using inpolygon, and calculate the surface based on all points, which will be NaN for points outside the polygon.

    From your example:

    % Input function and polygon for an example
    f =@(x,y) x.*y;
    % Polygon is [x, y] points
    p = [0 0
         1 0
         2 2
         0 1];
    
    % Generate a x-y mesh for the bounding box of a polygon
    n = 1000; % Number of points in each direction
    x = linspace( min(p(:,1)), max(p(:,1)), n ); % Grid points for x
    y = linspace( min(p(:,2)), max(p(:,2)), n ); % Grid points for y
    [x,y] = meshgrid( x, y ); % All x-y combinations for grid
    
    b = inpolygon( x, y, p(:,1), p(:,2) ); % Check which points are in the polygon
    x(~b) = NaN; % Make points outside the polygon equal to NaN,
    y(~b) = NaN; % so that f(x,y) is also NaN
    
    % Plot the patch of the original polygon and the surface f(x,y)
    figure(1); clf; hold on; grid on;
    patch( p(:,1), p(:,2), 'k', 'displayname', 'x-y poly' );
    surf( x, y, f(x,y), 'displayname', 'f(x,y) in poly', 'edgecolor', 'flat' );
    legend( 'show', 'location', 'north' ); view( 6, 25 ); colormap( 'jet' );
    

    Example output:

    Surface with bounding polygon