Parametric equation of rectangle given its centre and side length

1.6k Views Asked by At

This question is related to answer provided by user58347 to question Equation of a rectangle asked by Cobold.

I used the provided equation for generating rectangle given its centre and side length by modifying it slightly as shown below.

\begin{align} x(t) &= x_c + \frac{1}{2}\cdot w\cdot \mathrm{sgn}(\cos(t)),\\ y(t) &= y_c + \frac{1}{2}\cdot h\cdot \mathrm{sgn}(\sin(t)). \end{align} for $0 \leq t \leq 2\pi$

Above equation has been implemented as a function in MATLAB as shown below:

function H = drawrect(xc,yc,w,h)
%Generate linearly spaced vector t from 0 to 2*pi with 100 points
t=linspace(0,2*pi);
% Generate vector x and y
x = xc + 0.5*w*sign(cos(t));
y = yc + 0.5*h*sign(sin(t));
% Plotting them
H = plot(x,y);

Note that I've set variable $t\in[0,2\pi]$. On calling above function in MATLAB command window as

drawrect(-1,0.5,2,1);
axis([-3 3 -3 3]);
grid on;

results into

enter image description here

As seen from the above plot. The rectangle is not complete. So I just incremented $t$ slightly as shown in edited code as

function H = drawrect(xc,yc,w,h)
%Generate linearly spaced vector t from 0 to 2*pi with 100 points
t=linspace(0,2.1*pi);
% Generate vector x and y
x = xc + 0.5*w*sign(cos(t));
y = yc + 0.5*h*sign(sin(t));
% Plotting them
H = plot(x,y);

Which results into a perfect rectangle! Why is it so? enter image description here

1

There are 1 best solutions below

1
On BEST ANSWER

Frankly I don't understand why one would want to use all that code to generate a list of $4\times25$ repetitions of the vertices coordinates. Writing as follows:

function H = drawrect(xc,yc,w,h)
x=[xc + 0.5*w, xc - 0.5*w, xc - 0.5*w, xc + 0.5*w, xc + 0.5*w]
y=[yc + 0.5*h, yc + 0.5*h, yc - 0.5*h, yc - 0.5*h, yc + 0.5*h]
H = plot(x,y);

should give the same result.

Anyway, back to your question, the reason is probably in the way MATLAB handles the number $\pi$. I don't have that software at hand, but you can check whether sign(sin(2pi)) gives zero (as it should) or not. To solve the problem, simply avoid starting with $0$: you could use for instance t=linspace(1,2*pi+1).