MatLab question: The vector x contains the side lengths for some unknown shape.
ID: 3872058 • Letter: M
Question
MatLab question:
The vector x contains the side lengths for some unknown shape. If x contains 3 side lengths, then x represents a triangle. Moreover, if all the elements of x are equal, then x represents an equilateral triangle.
Using a series of if, elseif, and else statements, identify the most specific shape that x describes from the following:
triangle
equilateral triangle
quadrilateral
rhombus
polygon (for more than 4 sides)
n/a (for less than 3 sides)
Assign your answer as a string to the variable s.
Matlab functions all(), numel(), length() may be helpful.
Explanation / Answer
The Matlab function FindShape.m
function s = FindShape(x)
% FindShape is a matlab function to determin the shape using the input
% vector x contains the side lengths for some unknown shape. The result
% is stored in the output variable s.
v = sum(diff(x(x~=0))); % v = 0 if all nonzero sides are equal else v is nonzero
if all(x) % if all(x) is one, there is no side with zero length
n = length(x); % counting the number of sides
else % if all(x) is zero, then there is atleast one side with zero length
n = sum(x~=0); % counting the number of sizes by eliminating side with zero length
end % end of counting number of side of the shape
if n < 3 % if number of sides is less than 3 then
s = 'n/a'; % s is n/a as given in
elseif (n == 3) && (v ~= 0) % if number of sides are 3 and sides are not equal
s = 'triangle'; % then s is triangle.
elseif (n == 3) && (v == 0) % if number of sides are 3 and sides are equal
s = 'equilateral triangle'; % then s is equilateral triangle
elseif (n == 4) && (v ~= 0) % if number of sides are 4 and sides are not equal
s = 'quadrilatera';% then s is quadrilatera
elseif (n == 4) && (v == 0) % if number of sides are 4 and sides are equal
s = 'rhombus'; % then s is rhombus
elseif n > 4 % for number of edges are more than 4 then
s = 'polygon'; % the shape is polygon
end % end of if elseif
end % end of function
Sample OUTPUTS
>> x = [1 1];
>> s = FindShape(x)
s =
n/a
>> x = [1 1 0];
>> s = FindShape(x)
s =
n/a
>> x = [1 1 1];
>> s = FindShape(x)
s =
equilateral triangle
>> x = [1 1 2];
>> s = FindShape(x)
s =
triangle
>> x = [1 1 2 5];
>> s = FindShape(x)
s =
quadrilatera
>> x = [2 2 2 2];
>> s = FindShape(x)
s =
rhombus
>> x = [2 2 2 2 0 0];
>> s = FindShape(x)
s =
rhombus
>> x = [2 2 2 2 2 2];
>> s = FindShape(x)
s =
polygon
>>