Plotting a grid of squares in MATLAB
12,479
Solution 1
This looks like a problem I had to solve. What I do below is get the coordinates of all the points with meshgrid. Then I get the distance from everey point to every other point with pdist, when the distance is 1 its is a connection we want to draw. Then we plot all those lines.
%# enter your prerequisites
I=400; R=0.1; N=sqrt(I); M=sqrt(I);
%# create vertices on square grid defined by two vectors
[X Y] = meshgrid(1:N,1:M); X = X(:); Y = Y(:);
%# create adjacencymatrix with connections between all neighboring vertices
adjacency = squareform( pdist([X Y], 'cityblock') == 1 );
%# plot adjacenymatrix on grid with scale R and origin at the center
[xx yy] = gplot(adjacency, [X Y]);
xx = xx-round(sqrt(I)/2); %# this centers the origin
yy = yy-round(sqrt(I)/2);
plot(xx*R, yy*R)
Solution 2
You can generate the grid with the right number of vertical and horizontal lines:
%%
N = 400;
x = linspace(-1,1,sqrt(N)+1)
y = linspace(-1,1,sqrt(N)+1)
% Horizontal grid
for k = 1:length(y)
line([x(1) x(end)], [y(k) y(k)])
end
% Vertical grid
for k = 1:length(y)
line([x(k) x(k)], [y(1) y(end)])
end
axis square
Solution 3
See the rectangle function. For example, try
% Draw large bounding box:
xstart = -1;
ystart = -1;
xlen = 2;
ylen = 2;
rectangle('position', [xstart, ystart, xlen, ylen])
% Draw smaller boxes
dx = 0.1;
dy = 0.1;
nx = floor(xlen/dx);
ny = floor(ylen/dy);
for i = 1:nx
x = xstart + (i-1)*dx;
for j = 1:ny
y = ystart + (j-1)*dy;
rectangle('position', [x, y, dx, dy])
end
end
Author by
Bektaş Şahin
Updated on June 04, 2022Comments
-
Bektaş Şahin almost 2 years
I would like to plot a square in a 2D cartesian coordinate system with its corners at
(±1,±1)
. I would like to further divide it to 400 smaller and equal squares each with an edge length of0.1
.How can I do this in MATLAB?
-
Itamar Katz over 12 yearsWhat did you try so far? What didn't work?
-