Meshgrid with a hole in MatLab

245 Views Asked by At

enter image description here

I am trying to create a meshgrid with a hole in MatLab using meshgrid command. Rectangular plate grid is very easy but excluding points inside the hole boundary, I have difficulty!

"I want to exclude the little black disks (dont use the word ¨points¨) falling entirely inside the large disk".

"little black disks" are points whose (x,y) coordinates are being used for computation.

"large disk" is the hole (discontinuity).

Plate can be considered as 80 by 60 and hole located at (30,40) radius 10.

Thank you.

2

There are 2 best solutions below

0
On BEST ANSWER
% Circular Hole C1
    % Radius
    a = 5;
    % Centre
    Xc1 = 10;
    Yc1 = 20;
    %-------------------------
    
    % Coordinates of Lower Left corner
    LLx = -30;
    LLy = -30;
    
    % Coordinates of Upper Right corner
    URx = 60;
    URy = 60;
    
    % Number of points in rectangle
    nopRECT = 1001;
    rectangleX = linspace(LLx,URx,nopRECT);
    rectangleY = linspace(LLy,URy,nopRECT);
    
    [xGRID,yGRID] = meshgrid(rectangleX,rectangleY);
    
    [ROW1,COL1] = size(xGRID)
    size(yGRID)
    
    % Circular Hole 1
    r_a = linspace(0,(a-0.01*a),nopRECT);
    t_a = linspace(0,2*pi,nopRECT);
    
    [ra tha] = meshgrid(r_a,t_a);
    
    C1x = Xc1 + ra.*cos(tha);
    C1y = Yc1 + ra.*sin(tha);
    
    TrackerMatrix = zeros(ROW1,COL1);
    
    for i = 1:ROW1
        for j = 1:COL1
            
            xP = xGRID(i,j);    % x-coordinate of point P at (i,j)
            yP = yGRID(i,j);    % y-coordinate of point P at (i,j)
            
            dist1 = sqrt((xP-Xc1)^2+(yP-Yc1)^2);    % Distance of point P from center of C1
            
            if dist1 >= a
                % When point is outside of Hole 1
                TrackerMatrix(i,j) = 1;
            else
                % When point is inside of Hole 1
                TrackerMatrix(i,j) = 0;
                xGRID(i,j) = nan;
                yGRID(i,j) = nan;            
            end
    
        end % loop j
    end % loop i
0
On

Note that determining whether a point (x, y) lies within an arbitrary boundary is generally much easier than determining whether a disk of small radius with center (x, y) lies within that boundary. When the boundary in question is also a disk, both questions are simple.

Using Boolean operators on the outputs of meshgrid to create a mask could be sufficient. For example:

function mask = is_excluded(x, y)
  % "radius" of the little black disks
  epsilon = 0.8;

  % discontinuity location
  disc_x = 30;
  disc_y = 40;
  disc_r = 10;

  % we benefit from the fact the all entities considered are circles
  mask = find((x - disc_x).^2 + (y - disc_y).^2 < (disc_r - epsilon)^2);
end

[xs, ys] = meshgrid(1:80, 1:60);
mask = is_excluded(xs, ys);

Then,

xs(mask) = NaN;
ys(mask) = NaN;
data = do_calculate(xs, ys);

Or,

data = NaN(size(xs));
data(~mask) = do_calculate(xs(~mask), ys(~mask));