Edit: MATLAB. I'm trying to create a function which returns an array of the velocity per second for a free falling object. The input argument for the function is the height h. Also, if the object hits the ground before 1 second, it should return the velocity for the time it hits the ground.
Example: If the object falls from 80 meters, the function should return
v =
9.8 19.6 29.4 39.2
My attempt looks like this:
function freefall(h)
g = 9.8; % gravity acceleration
h_t = linspace(0,h); % the height should start from 0 to input height h
t = sqrt(2.*h_t/g); % time for the free fall
n=0;
if t < 1
velocity = sqrt(2*g*h)
disp(velocity)
else
for time = n 1 % An attempt to try making t into integers(tried floor(t) but didn't work)
v = g.*time
while time <= t % Don't want the time to exceed the amount of time it takes for object to land
disp(v)
end
end
end
end
The output just becomes v = 9.82, and I'm out of ideas to try and make this work.
CodePudding user response:
I don't have matlab or scilab at the moment so I fiddled around using online scilab to write some test code. Here what I came up with:
function freefall(h)
g = 9.8;
s = sqrt(2*h/g);
t = floor(s);
t_mat = linspace(1, t, t);
t_mat = g * t_mat;
return t_mat;
end
You can then call that function this way:
ans = freefall(80);
disp(freefall(80));
What's missing on your code is rather to limit the increments of linspace
, for some odd reason you tried to compare a vector
to a scalar
(that if t < 1
on your code), and finally your function did not return
an answer, instead it prints it.
¯\(ツ)/¯ correct me if I'm wrong, I haven't write any matlab code for like 6 years.
Note: that online scilab doesn't seem to support function so, you have to use bare code without the function block. You can replace that return
with disp(t_mat)
.
CodePudding user response:
Is this all you are trying to do?
tfinal = sqrt(2*h/g); % time to fall to ground
if tfinal < 1
velocity = g*tfinal; % velocity when hitting ground is less than 1 sec
else
velocity = g*(1:tfinal); % velocities at 1 sec intervals, not including hitting ground
end
If you always wanted to include the final velocity in the output, you could do this instead:
tfinal = sqrt(2*h/g); % time to fall to ground
t = 1:tfinal; % range of integer times spaced by 1 sec
if tfinal ~= fix(tfinal) % if final time is not an integer
t = [t,tfinal]; % append final time to time array
end
velocity = g*t; % velocities at integer times plus final time