What is the output after each recursive function call?

조회 수: 1 (최근 30일)
Camden Nelson
Camden Nelson 2023년 5월 8일
댓글: Jonas 2023년 5월 8일
Consider the following code:
function [out] = myRecurfn(num)
if floor(num) == 0
out = 2
else
out = 4 + myRecurfn(num-1)
end
end
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
Jonas
Jonas 2023년 5월 8일
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

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2023년 5월 8일
"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
sin(pi)
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.
myRecurfn(3.5);
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;
else
out = 4 + myRecurfn(num-1);
end
disp(out) % display the function output
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by