Pyth. theorem script. Complex numbers exclusion. For the Type==1 when real part is positive the exclusion does not work. Any ideas why? Any idea also for characters exclusion?
2 views (last 30 days)
Show older comments
clc, clear all
Type = input("Give 1 for Hypotenuse or 2 for Vertical : "); % Asking user for Hypotenuse or Vertical
if Type == 1 %User wants to find hypotenuse
sides = input("Give [side1 side2] = ");
if sides(1,1)>0 && sides(1,2)>0
Hyp = sqrt(sides(1,1)^2 + sides(1,2)^2) %Calculation of the hypotenuse if both sides are given positive
elseif sides(1,1)<0 || sides(1,2)<0 || sides(1,1) == complex(sides(1,1)) || sides(1,2) == complex(sides(1,2))
disp('Negative or complex values for lengths are not allowed!!') %Displays that the sides cannot be negative neither complex numbers
elseif sides(1,1) == 0 && sides(1,2) == 0
Hyp = sqrt(sides(1,1)^2 + sides(1,2)^2)
disp('The triangle became a single point') %Displays what happens when both vertical sides are zero
else
Hyp = sqrt(sides(1,1)^2 + sides(1,2)^2)
disp('The triangle became a straight line') %Displays what happens when only one vertical side is zero
end
elseif Type == 2 %User wants to find a vertical side
sides = input("Give [Hyp side] = ");
if sides(1,1)<0 || sides(1,2)<0 || sides(1,1) == complex(sides(1,1)) || sides(1,2) == complex(sides(1,2))
disp('WARNING! Negative or complex values for lengths are not allowed!!') %Displays that the sides cannot be negative neither complex numbers
elseif sides(1,1) == 0 && sides(1,2) == 0
Vert = sqrt(sides(1,1)^2 - sides(1,2)^2)
disp('The triangle became a single point') %Displays what happens when both Hyp and vertical are zero
elseif sides(1,1)>0 && sides(1,2)>0 && sides(1,1)>sides(1,2)
Vert = sqrt(sides(1,1)^2 - sides(1,2)^2) %Calculation of the vertical side when the sides are both positive and the hypotenuse is greater than the vertical
else
disp('Hyp must be GREATER than the given side') %Displays what happens when Hyp is less than the vertical side
end
else
disp('Wrong Input') %Displays what happens when the user enters a number different than 1 or 2
%pyth
end
0 Comments
Accepted Answer
Walter Roberson
on 19 Dec 2021
When you use the < <= > >= then matlab only compares real parts.
You should first test if any(imag(sides)) then there is a complex component
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!