fiorie
fiorie

Reputation: 11

How to plot 4 separate lines to form a square in MATLAB?

I am plotting 4 random separate lines in a plot, and I want them to be connected to form a square. This is what I've got so far, any pointers would be really helpful. Also, this is my first time using MATLAB so please don't come for me.

N = 1;
L = 0.2;


x = L +rand(1,N)*(1-2*L);
y = L +rand(1,N)*(1-2*L);


angs = rand(1,N)*360;

xe = x - L*cosd(angs);
ye = y + L*sind(angs);
xb = -x - L*cosd(angs);
yb = y +  L*sind(angs);

ax = axes;

plot(ax,[x;xe],[y;ye],[x;xb],[y;yb])

axis square

I need them to be 4 lines of the same length that join to make a square. The above code gives me 2 connecting lines but I really don't know where to go from there.

My attempt of the above code: My attempt of the above code

Upvotes: 1

Views: 478

Answers (1)

pho
pho

Reputation: 25500

The plot function simply plots the x- and y- coordinates that you give it. Giving it the correct coordinates to plot is your job. So how would you figure out the coordinates of a square, given a starting point and the length and direction of one of the sides?

Suppose we have

p0 = rand(1, 2); % p0(1) => x; p0(2) => y
L = 10;
d0 = rand(1, 2); % The direction vector. 

First, let's convert the direction into a unit vector.

u_vec = d0 ./ norm(d0);

Next, let's rotate this vector by 90 degrees to get the unit vector for the perpendicular side

u_perp = ([0, -1; 1 0] * u_vec')';

Using vector addition, we know that the second point is p1 = p0 + L * u_vec. The third point is p2 = p1 + L * u_perp, and the final point is p3 = p_0 + L * u_perp. We can stack these vectors just to make it easier to type out the plotting code:

l1 = [p0; p1];
l2 = [p1; p2];
l3 = [p2; p3];
l4 = [p3; p0];

And finally plot them:

figure();
hold on;
plot(l1(:, 1), l1(:, 2));
plot(l2(:, 1), l2(:, 2));
plot(l3(:, 1), l3(:, 2));
plot(l4(:, 1), l4(:, 2));
axis square;

enter image description here

Or, you could stack everything into one array and plot using a single line:

sq = [p0; p1; p2; p3; p0];
figure();
plot(sq(:, 1), sq(:, 2));
axis square;

enter image description here

Upvotes: 1

Related Questions