Trying to find if three inputed numbers can make a right triangle
6 views (last 30 days)
Show older comments
Can anyone help? I am trying to see if an array of three numbers inputted by a user can form a right triangle. My code is below and I can't figure out why it won't work. Thank you in advance!
sides =input('please enter 3 whole numbers in brackets [] : ');
Sides = perms(sides);% generate an array of the permutations of the input
Triange=0% initiate count
for a = 1:3
for b = 1:3
for c = 1:3
if (Sides(:,a)^ 2)+ (Sides(:,b)^ 2) == (Sides(:,c) ^ 2);
Tri(:,:) = [Sides(:,a),Sides(:,b),Sides(:,c)];
Triangle=Triangle +1
else disp('there are no right triangles')
end
end% for c
end% for b
end%for a
0 Comments
Accepted Answer
Star Strider
on 24 Oct 2015
It is difficult for me to follow your code. I would do it this way:
sortsides = sort(sides);
istri = sum(sortsides(1:2)) >= sortsides(3); % Will The 3 Numbers Form A Triangle?
isrightri = sum(sortsides(1:2).^2) == sortsides(3).^2; % Is It A Right Triangle?
if isrightri
fprintf('\n\tThe numbers {%d, %d, %d} form a right triangle.\n', sortsides)
elseif istri && ~isrightri
fprintf('\n\tThe numbers {%d, %d, %d} do not form a right triangle.\n', sortsides)
elseif ~istri
fprintf('\n\tThe numbers {%d, %d, %d} do not form any triangle.\n', sortsides)
end
The ‘sortsides’ assignment sorts the sides in ascending order. This is important for the efficiency of the code! If the sum of the lengths of the two shorter sides is greater that the length of the third side, then you can form a triangle (the istri assignment), otherwise it is impossible to form any triangle from them. Then determine if it is a right triangle, using the Pythagorean Theorem.
2 Comments
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!