如何在Matlab中获取中心点的正方形?

时间:2017-06-04 14:45:39

标签: matlab plot

我想绘制由其中心点定义的几个方块。这是我目前的代码:

x1=0;
x2=1;
y1=0;
y2=1;
x = [x1, x2, x2, x1, x1];
y = [y1, y1, y2, y2, y1];
plot(x, y, 'b-', 'LineWidth', 3);
hold on;
x1=0.25;
x2=.75;
y1=0.25;
y2=.75;
x = [x1, x2, x2, x1, x1];
y = [y1, y1, y2, y2, y1];
plot(x, y, 'b-');
xlim([-1, 2]);
ylim([-1, 2]);

我想在表单中使用它:

points  = [1,4];
lengthSquare = 5;
square(points, lengthSquare);

1 个答案:

答案 0 :(得分:1)

这样的事情应该有效。它基于我之前给出的hexagons

的回答
function square( centers, sides )
h = figure(47);
close(h)
h = figure(47);

nSides = 4; % number of sides of regular polygon
rot = 0;    % rotation angle in degrees

% every polygon has the same side length?
if length(sides) == 1
    sides = sides * ones(size(centers, 1),1);
end

x0 = centers(:,1);
y0 = centers(:,2);

filledShape = true;

[x, y] = arrayfun(@(X0, Y0, S) vertexCoords(X0, Y0, S, nSides, ~filledShape, rot), x0,y0,sides, 'uni', 0);

if filledShape
    for i = 1:length(x)
        patch('Faces', 1:length(x{i}), 'Vertices', [x{i}, y{i}],'FaceColor','red')
    end

else
    T = [x, y]';
    plot(T{:},'LineWidth',2)
end

axis equal

end

function [x, y] = vertexCoords(x0, y0, s, nSides, rot, closed)
        %Need nSides+1 to close the figure.
        theta = linspace(0, 2*pi, nSides+1)' - (pi/nSides) - rot;

    if ~closed
        theta(end) = [];
    end

    % convert from side length to diameter
    D = 2*s ./ sqrt(2 - 2*cos(2*pi/nSides));

        %Convert from polar to Cartesian coordinates 
        x = D/2 * cos(theta) + x0;
        y = D/2 * sin(theta) + y0;
end