Recursive method from for loop
12 ビュー (過去 30 日間)
古いコメントを表示
Martynas Tirlikas
2017 年 10 月 1 日
回答済み: Walter Roberson
2017 年 10 月 1 日
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
0 件のコメント
採用された回答
Walter Roberson
2017 年 10 月 1 日
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.
0 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!