I'm trying to plot a square on Matlab, specifically using the line
command, with corners at the points (0,0), (0, rho), (rho, 0) and (rho, rho)
% create axes
x = linspace(0,10,100);
y = linspace(0,20,100);
rho = 2*pi;
% plot
figure;
A = line([0 0],[0 rho]);
B = line([0 0],[rho 0]);
C = line([0 rho],[rho rho]);
D = line([rho 0],[rho rho]);
fill(A,B,C,D,'b');
However, line D
fails to appear in my figure and moreover, the fill
command is not working, although that part is really quite optional. My main issue is why the aforementioned line won't appear in the plot
That's because you aren't specifying the coordinates for the box properly. Remember that line
takes in two vectors where the first vector is a list of x
coordinates and the second vector is a list of y
coordinates. Each ith pair of (x, y)
will have a line drawn from its previous (i-1)th point up to the ith point except for the first point of course. The lines drawn by A
and B
are the same line. The same can be said with C
and D
. It's just a matter of modifying the statements so you're drawing the line correctly.
Drawing the box in lovely ASCII graphics for illustration:
(0, rho) (rho, rho)
------------------------
| |
| |
| |
| |
------------------------
(0, 0) (rho, 0)
You need to draw four lines. Let's traverse counter-clockwise:
(0, 0)
to (0, rho)
(0, rho)
to (rho, rho)
(rho, rho)
to (rho, 0)
(rho, 0)
to (0, 0)
Therefore, modify your code to be:
rho = 2*pi;
A = line([0 0],[0 rho]);
B = line([0 rho],[rho rho]);
C = line([rho rho],[rho 0]);
D = line([rho 0],[0 0]);
BTW, the code above may not be portable for later. You are going to get line handles which is fine by you don't use this as an input into fill
.
We finally get:
It may be cleaner to just put all of the coordinates in just two vectors and call line
. This will also make this play nicely with fill
:
rho = 2*pi;
x = [0, 0, rho rho, 0];
y = [0, rho, rho, 0, 0];
line(x, y);
hold on;
fill(x, y, 'b');
Notice that we use the proper convention for line
, then draw it, then we fill it. If you follow the logic specified earlier, we draw a line from (0, 0)
to (0, rho)
, then from (0, rho)
to (rho, rho)
, then from (rho, rho)
to (rho, 0)
then finally from (rho, 0)
back to (0, 0)
. Notice that we had to use the origin (0, 0)
at the beginning and at the end to ensure that we draw the line at the bottom edge of the square. We also use hold on
to add the filled box in after the square boundary that you've drawn on the figure. fill
takes in a vector of coordinates just like line
does. We get: