MATLAB: Issue splitting a scirpt into a script and function

ballfunctionsphysics

So I currently have a script that throws a ball at a set inital height h, velovity v and angle theta. It also returns the value of x at which the ball hits the ground and plots the path it takes when it is finished. I now must turn it into a function and have the user input the starting velocity and angle and return a value called distance and plot the in a seperate script. I'm having issues with getting the returned value back and am unsure how to use it effectivly. g is to print a black dashed line All I know is I am not suppsoed to plot the graph inside the function. Help would be much appreciated. My old code lookes like
h=1.5;
a=9.8;
v=4;
theta=pi/4;
t=0:0.001:1;
x=v*cos(theta).*t;
y=h+v*sin(theta).*t-0.5*a*t.^2;
ypos=find(y < 0, 1);
xpos=x(:,ypos);
g=zeros(1,length(x));
fprintf('The ball hit the ground at %0.4f meters. \n', xpos);
figure
hold on
plot(x,y)
plot(x,g,'--', 'color', 'black')
xlabel('Distance (m)')
ylabel('Height (m)')
title('Ball trajectory')

Best Answer

Simply write this:
function distance = throwBall(v,theta)
h=1.5;
a=9.8;
t=0:0.001:1;
x=v*cos(theta).*t;
y=h+v*sin(theta).*t-0.5*a*t.^2;
ypos=find(y < 0, 1);
distance=x(:,ypos);
g=zeros(1,length(x));
fprintf('The ball hit the ground at %0.4f meters. \n', distance);
figure
hold on
plot(x,y)
plot(x,g,'--', 'color', 'black')
xlabel('Distance (m)')
ylabel('Height (m)')
title('Ball trajectory')
end
and call it from command line as
distance=throwBall(4,pi/4)
and observe the results.