I want to know if there are any ways to plot a given function with 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 have no idea on how to use it to plot a function only inside the polygon.
Thanks in advance.
You can generate a mesh for x-y points in the bounding box of your polygon, then make points outside the polygon equal to NaN
using inpolygon
, then calculate the surface based on all points, which will be NaN
for points outside the polygon.
From your example:
% Input function and polygon for example
f =@(x,y) x.*y;
% Polygon is [x, y] points
p = [0 0
1 0
2 2
0 1];
% Generate x-y mesh for bounding box of 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: