You have
function averagespeed = speed(time, distance)
for i=1:1:8
dis = 0.9^(-i) * distance(i);
ti = 0.9^(-i) * time(i);
totaldistance = dis+totaldistance;
totaltime = ti+totaltime;
averagespeed = speed + totaldistance/totaltime;
end
end
In the line
averagespeed = speed + totaldistance/totaltime;
you have a reference to the function speed, but you are not passing in the time and distance parameters that speed() needs.
Recursive functions always need to have a test for some boundary condition under which they can return a value directly instead of calling itself recursively, and ideally you should be able to give a proof by induction that every branch of the recursion will eventually stop. For example,
function averagespeed = speed(time, distance)
if time <= eps
averagespeed = 0.0;
return
end
for i=1:1:8
dis = 0.9^(-i) * distance(i);
ti = 0.9^(-i) * time(i);
totaldistance = dis+totaldistance;
totaltime = ti+totaltime;
averagespeed = speed(time/2, distance/2) + totaldistance/totaltime;
end
end
Note, though, that you are adding dis to totaldistance before having defined totaldistance inside the function. Perhaps you thought you were using totaldistance as a shared variable, but shared variables need to have been defined inside an outer function and your outer code is a script not a function. Writing to a shared variable (other than perhaps a counter) is more often than not a mistake in a recursive routine, better handled by returning multiple outputs from the recursive routine.
