我想在2D笛卡尔坐标系中绘制一个正方形,其角点位于(±1,±1)
。我想进一步将其划分为400个较小且相等的正方形,每个正方形的边长为0.1
。
我怎样才能在MATLAB中做到这一点?
答案 0 :(得分:2)
您可以生成具有正确数量的垂直和水平线的网格:
%%
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
答案 1 :(得分:2)
这看起来像我必须解决的问题。我在下面做的是使用meshgrid获取所有点的坐标。然后我通过pdist得到从everey点到每个其他点的距离,当距离为1时,它是我们想要绘制的连接。然后我们绘制所有这些线。
%# 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)
答案 2 :(得分:1)
请参阅rectangle功能。例如,尝试
% 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