在 MATLAB 中绘制多边形内的函数

53 阅读1分钟

可以为多边形边界框中的 xy 点生成网格,NaN使用使多边形外的点等于inpolygon,并根据所有点计算表面,这些点将NaN用于多边形外的点。

例子来看:

% 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' );

示例输出:

82g33rmT.png

MATLAB R2023a