Code review: Inputing coordinates and calculating triangle parameters.

15 views (last 30 days)
WONG SIAN on 18 Feb 2011
Edited: Roger Stafford on 26 Apr 2014
A figure shows a triangle defined by the vertex coordinates (x1 ,y1 ) ,(x2 ,y2 ) , and (x3 ,y3 ). What command will interactively prompt a user for x and y coordinates at each of the triangle vertices. then how about draw the triangle and label it vertices. Next is compute and print the area of the triangle and its perimeter.
My solution is like this, please check for me ya...
x1=input('x1=');
y1=input('y1=');
x2=input('x2=');
y2=input('y2=');
x3=input('x3=');
y3=input('y3=');
v1=[x1 y1];
v2=[x2 y2];
v3=[x3 y3];
a=sqrt((x1-x2)^2+(y1-y2)^2);
b=sqrt((x2-x3)^2+(y2-y3)^2);
c=sqrt((x3-x1)^2+(y3-y1)^2);
if a > 0 & b > 0 & c > 0 & (a + b > c) & (a + c > b) & (b + c > a)
s=(a+b+c)/2;
Area=sqrt(a*(s-a)*(s-b)*(s-c))
Perimeter=a+b+c
plot([x1 x2 x3 x1],[y1 y2 y3 y1])
title('Triangle')
xlabel('x axis')
ylabel('y axis')
text(x1,y1,sprintf('(%d,%d)',x1,y1))
text(x2,y2,sprintf('(%d,%d)',x2,y2))
text(x3,y3,sprintf('(%d,%d)',x3,y3))
else
end
2nd question is about plotting functions :
How to create a variable t that takes values from 0 to 2pie with step size 0.001 . I already given de value of y. I wish to know how to plot and versus t in separate figures. What about plot and versus t in the same figure and use different colour for each graph and label each of them.
Then if I want to divide a figure in two by using the subplot command, then plot and in the upper part and in the lower part which all plots versus t. how ya??
Thanks..
Doug Hull on 18 Feb 2011
Please, only one question per question. You should edit this question and add a second separate one.

Roberto on 26 Apr 2014
Hope this will help:
h = gca ;
cla ;
hold on ;
axis([0 10 0 10]);
for i = 1 : 3
coord(i,:) = ginput(1) ;
plot(coord(i,1),coord(i,2),'o','MarkerSize',10) ;
text(coord(i,1),coord(i,2),['p' num2str(i) '(' num2str(coord(i,1)) ',' num2str(coord(i,2)) ')'] );
end
fill(coord(:,1),coord(:,2),'r');

Roger Stafford on 26 Apr 2014
Edited: Roger Stafford on 26 Apr 2014
1) The area formula has an error. The first factor should be s, not a.
2) There is a somewhat more robust area formula using the vertices' coordinates directly:
area = abs((x2-x1)*(y3-y1)-(x3-x1)*(y2-y1))/2;
3) It is unnecessary to perform those inequality tests, since the lengths a, b, and c were computed from entered coordinates which imply them.
4) Hmm. This is a truly ancient question - Feb 2011