如何在Matlab中用求中心点绘制正方形?
我想画几个由中心点定义的正方形。这是我目前的代码:如何在Matlab中用求中心点绘制正方形?,matlab,plot,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-'); x
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);
这样的办法应该行得通。这是基于我之前的回答
如何填充正方形?如果您想填充,请使用
fill
或patch
而不是plot
。我在square
函数中对这两个参数进行了treid,但显示:输入参数不够。我对答案进行了更改,但您不应该回来说“它不起作用”您应该查看文档(只需在遇到问题的函数上点击F1)
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