How can I "draw" a 2D figure if I know all of its points?

77 views (last 30 days)
Hi everybody,
I'm an amateur at MATLAB and I know how to do the basic stuff such as plotting functions, writing M files, functions, for loops, etc but I've be tasked to do something I have never done before.
I have to draw this figure which resembles a Tree or Home (2D childs drawing), and I know all of its points: (6,1), (8,1), (6, 3) (8,3) makes the base of the house (and the diagonals are drawn too) and then the points (6,3), (7,4), (8,3) make the roof.
How do I connect the points in a way that it resembles what I'm looking at?
Joe on 7 Oct 2014
This is what I currently have, which is manually entering each point
This is what I currently have:
clear all;
plot([6 8],[1 1]);
grid on;
axis([5 9 0 5]);
hold on;
plot([6 8],[3 3]);
plot([6 6], [1 3]);
plot([8 8], [1 3]);
plot([6 8], [3 1]);
plot([6 8], [1 3]);
plot([6 7], [3 4]);
plot([7 8], [4 3]);
But I'm wondering if there's a faster, more efficient way to do this

Sign in to comment.

Accepted Answer

Andrew Reibold
Andrew Reibold on 7 Oct 2014
Edited: Andrew Reibold on 7 Oct 2014
The greyed out text is all you should have to type to make what you want.
First assign the data to an 'array', or also called a 'matrix' by using the brackets and syntax below. There are dozens of ways to do this, but for now I will cheat and enter points in manually. I will split up the arrays a bit for clarity even though it would be more efficient to combine them.
base_x = [6 8 8 6 6 8 6 8]
base_y = [1 1 3 3 1 3 3 1]
roof_x = [6 7 8 6]
roof_y = [3 4 3 3]
The way the Matlab plot command works is kind of like 'connect-the-dots', so thats why some of the points were duplicated (to make the diagonals).
Next I open a figure window (where the graph will pop up) using figure , and tell the graph that its ok to plot multiple things by using hold on. By default you can only plot one thing at a time and when you plot two or more things the previous is erased.
The plot command has two inputs in parenthesis right after you call it, the first input is your x-coordinates and the second input is your y-coordinates. It plots them in order. I added '-' because it tells the plot command to draw lines between the points. I also use the axis command to set the range of what is visible (gave some extra room around the house)
hold on
plot(base_x, base_y,'-')
plot(roof_x, roof_y,'-')
axis([5 9 0 5])
Wallah, you have a house. There are tons of things you can do with regard to color, putting stars or crosses at each point, and so on. That comes with practice or reading documentation and searching google.
Gerald Colyvas
Gerald Colyvas on 18 Apr 2018
Thanks. This has been helpful. one quick question though, how can I eliminate the diagonals?

Sign in to comment.

More Answers (0)


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by