What is the output after each recursive function call?

2 views (last 30 days)
Consider the following code:
function [out] = myRecurfn(num)
if floor(num) == 0
out = 2
out = 4 + myRecurfn(num-1)
When the above function is called with myRecurfn(3.5), what is the value of the output variable? Show your work, by showing what is ‘out’ for every call of the function and then how the final value is reached.
Since the value of out is only given for floor(num) == 0 (i.e. when num = 0.5) does that mean that the output for all the calls up to this point would just be: out = 4 + myRecurfn(3.5-1), out = myRecurfn(2.5-1), out = myRecurfn(1.5-1), and then the first output is out = 2? I am confused what is meant by a function call in this case, or what the output should look like for each call.
  1 Comment
Jonas on 8 May 2023
you are on the right way, but floor() does not mean -1 as you wrote. floor of 3.5 is 3, not 2.5.
floor calcultes the nearest smaller integer of the input if the input is not already integer
3.5 -> 3
2 -> 2
-1.5 -> -2
and so on

Sign in to comment.

Accepted Answer

Stephen23 on 8 May 2023
"I am confused what is meant by a function call in this case,"
A function call is every time a function is called. Usually functions are called by a user, e.g. when you write
in the command line you are calling the SIN function. Inside a recursive function, a function calls itself (but the meaning has not changed at all). Every time this line is evaluated:
out = 4 + myRecurfn(num-1)
the function is called... and theoretically might have an output (to which 4 is added). Your assignment asks for the values of each of those outputs. Use DISP to display the function outputs.
2 6 10 14
These ouput values correspond to input values of 0.5, 1.5, 2.5, and 3.5 respectively. Why are they in that order?: consider when the output values are defined: on the very first call (from you the user) is the output value already calculated? No, an actual number can only exist after all the recursive calls are complete... ditto every other call exept the deepest one. The deepest function call finally outputs a value, to which you add four, which can then be returned to its calling function (which happens to be itself)... etc.
function [out] = myRecurfn(num)
if floor(num) == 0
out = 2;
out = 4 + myRecurfn(num-1);
disp(out) % display the function output

More Answers (0)




Community Treasure Hunt

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

Start Hunting!