How can I get this function to take vector inputs for x

This function is to determine how much area a goat has to graze on when tied to a rope length x on the outside of a rectangular barn with sides length a and b. The rope can't be longer than a+b. It wont take vector inputs for x (to allow me to plot on a graph for a changing rope length) and I can't figure out why.
function[z] = goatgrazing(a,b,x)
if x <= a
if x <= b
z=(3/4).*pi.*(x).^2;
end
end
if x > a
if x <= b
z=(3/4).*pi.*(x).^2+(1/4).*pi.*(x-a).^2;
end
end
if x > b
if x <= a
z=(3/4).*pi.*(x).^2+(1/4).*pi.*(x-b).^2;
end
end
if x > b
if x > a
z = (3/4).*pi.*(x).^2+(1/4).*pi*(x-b).^2+(1/4).*pi.*(x).^2;
end
end
if x > a+b
error("These dimensions are not valid")
end
Also, any improvements to the code you could suggest would be appreciated.

 Accepted Answer

Use logical indexing. Your current code assumes that either x is a scalar or that exactly the same conditions apply to all x simultaneously.
mask = x > b & x <= a;
z(mask) = (3/4).*pi.*(x(mask)).^2+(1/4).*pi.*(x(mask)-b).^2;

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!