Recursive method from for loop

11 visualizzazioni (ultimi 30 giorni)
Hi!
I have a normal working loop
clc;
time = [0, 1, 2, 3, 4, 10, 12, 18];
distance = [4.71, 9, 15, 19, 20, 45, 55, 78];
totaltime = 0;
totaldistance = 0;
figure;
hold on
for i=1:1:8
dis = 0.9^(-i) * distance(i);
totaldistance = dis+totaldistance;
hold on
ti = 0.9^(-i) * time(i);
totaltime = ti+totaltime;
plot(ti,dis,'p')
hold on
plot(totaltime,totaldistance,'o')
hold on
end
v=totaldistance/totaltime;
estimatedspeed = v
plot(v,'*')
And I need to get the same result of estimated speed using recursive method. I'm a begginer in Matlab and I need a little bit of help. I tried to write a function as it would be recursive, but nothing goes right. Where I'm making a mistake?
clc;
time = [0, 1, 2, 3, 4, 10, 12, 18];
distance = [4.71, 9, 15, 19, 20, 45, 55, 78];
totaltime = 0;
totaldistance = 0;
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

Risposta accettata

Walter Roberson
Walter Roberson il 1 Ott 2017
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.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by