How to use recursion in MATLAB?

I have a simple m file that I created as a recursive function:

function[velocity] = terminal(m,c,t,vi)
%inputs:
% m = mass
% c = coeffcient of drag
% t = time
% vi = initial velocity

if t==18, velocity = vi+(9.8-c/m*(vi))*2;
    return 
end

velocity = vi+(9.8-c/m*(vi))*2;
velocity  %used to print out velocity for debugging
terminal(m,c,t+2,velocity);
end

The speed calculation is done correctly when it outputs each recursion. However, the "ans" that returns at the end is the first calculated recursion value. My question is: how to configure matlab function correctly recursively? Or can this be done, and is it better to use a loop?

+3
source share
4 answers

Bear with me, haven't done a lot of matlab for some time now.

But I would just call your function iteratively:

velocity = vi
for t = 0:2:18
    velocity = velocity+(9.8-c/m*(velocity))*2;
end

Then for each instance of t it will calculate the speed for a given initial speed and update it with a new speed.

2, .

+4

, , , , v(t) . , Stokes 'drag , , vFinal, tDelta vInitial. :

vFinal = 9.8*m/c + (vInitial - 9.8*m/c)*exp(-c*tDelta/m);

, vFinal, (.. , , ).

+6
velocity = terminal(m,c,t+2,velocity)

.

+1

. Matlab. , . , , . .

Finally, when you use recursion, learn when to use tools like memoization to improve algorithm behavior. Remembering simply means not repeating what you have already done. For example, you can use recursion for a Fibonacci sequence, but this is a terribly inefficient way to do this.

+1
source

Source: https://habr.com/ru/post/1786938/


All Articles