I have a square plane of size axa in Matlab (2D) and I want to create a meshgrid and put a hole in it of size bxb. My code seems to work, but looking closely it looks a bit strange. I'm new to Matlab.
The working code:
close all
clear all
a = 3;
b = 2;
number_of_gridcells = 150; % (both are the same since I will always have an outer square of axa)
% Create grid
wide = a; % m, plate width
high = a; % m, plate height
resX = number_of_gridcells; % number of grid points in X
resY = number_of_gridcells; % number of grid points in Y
[X,Y] = meshgrid(0:wide/resX:wide , 0:high/resY:high); % Creates a rectangular grid
% Remove an inner square of bxb
mask = abs(X - (a/2)) <= (b/2) & abs(Y - (a/2)) <= (b/2);
X(mask) = NaN;
Y(mask) = NaN;
% Initial condition (all equal)
Phi(1:resY+1,1:resX+1) = 0;
Phi0 = Phi; % initial condition preserved as Phi0
figure (1)
box on;
hold on;
set(gca,'FontSize',14);
lw = 1.5;
contourf(X, Y, Phi0, 20)
caxis([0 50])
colorbar('horiz')
axis equal
An example: for a=3 and b=2, I would expect a square of 3x3 with a wall thickness of 0.5.
This seems correct, but looking closer at the corners I see this:
First of all the corners are under an angle, while I was expecting just a 90 degree angle in the corners. Secondly, the corner starts at 0.5, but the wall itself is 0.48. So the wall is small than expected and thus the value for b is higher than expected.
I think it has something to do with how I create the mask in my code, but I am not sure how to fix this and if there is a better way to do this.
First of all the definition of your mask should be:
mask = abs(X - (a/2)) < (b/2) & abs(Y - (a/2)) < (b/2);
Otherwise the NaNs will also "sit" on the edge of your wall.
And second if you want to visualize just a plain surface on a grid, use surf()
or surface()
.
Contourf()
is used to draw isolines, that's why you see the rounded corner. The correct square hole should look like that: