【问题标题】:Plotting a grid of squares in MATLAB在 MATLAB 中绘制正方形网格
【发布时间】:2012-01-03 12:00:36
【问题描述】:

我想在二维笛卡尔坐标系中绘制一个正方形,其角为(±1,±1)。我想将其进一步划分为 400 个较小且相等的正方形,每个正方形的边长为 0.1

如何在 MATLAB 中做到这一点?

【问题讨论】:

  • 到目前为止你尝试了什么?什么不起作用?

标签: matlab plot geometry


【解决方案1】:

您可以生成具有正确数量的垂直和水平线的网格:

%%
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

【讨论】:

    【解决方案2】:

    这看起来是我必须解决的问题。我在下面做的是用meshgrid获取所有点的坐标。然后我用 pdist 得到每个点到每个其他点的距离,当距离为 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)
    

    【讨论】:

      【解决方案3】:

      请参阅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
      

      【讨论】:

        猜你喜欢
        • 2013-12-13
        • 2012-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-11
        • 2022-01-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多