MATLAB Answers

0

creating an equal lateral triangle in matrix

Asked by Nathan Sulzer on 10 Nov 2018
Latest activity Commented on by John D'Errico
on 10 Nov 2018
Is there an easy method for generating an equal lateral triangle centered and the middle of a matrix? The image attached is what I want the matrix to look like except the triangle would be made of 1s and the background zero. Thank you in advanced.

  0 Comments

Sign in to comment.

2 Answers

Answer by jonas
on 10 Nov 2018
Edited by jonas
on 10 Nov 2018

You could do something like this:
poly = polyshape([1 2 1.5],[1 1 2])
plot(poly)
set(gca,'xcolor','none','ycolor','none')
F = getframe(gca)
I = imbinarize(rgb2gray(F.cdata))
imshow(~I)
change coordinates of the polygon to create your desired triangle.

  1 Comment

Drat. Polyshape has not been around long enough that I think of it immediately. :)

Sign in to comment.


Answer by John D'Errico
on 10 Nov 2018

Any number of ways, certainly many if I spent any amount of time to think them up. Simplest?
1. Start with meshgrid, creating sets of indices into the final array.
2. Create a polygon, that denotes the corners of the triangle.
3. Use inpolygon to indicate which points lie inside the triangle.
4. Assign the array initially uing zeros.
5. Use logical indexing to overwrite the points inside the polygon as 1.
So simple and fast, fully vectorized. But many other ways too.

  0 Comments

Sign in to comment.