【问题标题】:How does Matlab's return control behave in a recursive function?Matlab 的返回控制在递归函数中如何表现?
【发布时间】:2018-07-26 21:57:57
【问题描述】:

它会返回递归函数还是调用递归函数的函数?

【问题讨论】:

  • 你试过了吗?
  • return: return 强制 MATLAB 在调用函数到达函数末尾之前将控制权返回给调用函数。 调用函数是调用脚本或函数的函数,其中包含对返回的调用。在对函数的第一次调用中,它会返回。之后,调用你的递归函数的函数就是递归函数本身。

标签: matlab recursion return


【解决方案1】:

在我看来,它会先回到递归函数。

一个小测试:

函数accu.m:

function [AN] = accu(num,an)
  disp(['recursive function with num = ' num2str(num)])
  if (num==0) 
      AN=an;
      return
  end
  AN=accu(num-1,an+num);
  disp(['recursive function with num = ' num2str(num) '.'])
end

当我们调用accu(5,0) 时,它会返回:

recursive function with num = 5
recursive function with num = 4
recursive function with num = 3
recursive function with num = 2
recursive function with num = 1
recursive function with num = 0
recursive function with num = 1.
recursive function with num = 2.
recursive function with num = 3.
recursive function with num = 4.
recursive function with num = 5.

ans =

    15

【讨论】:

    猜你喜欢
    • 2021-05-16
    • 1970-01-01
    • 2017-10-29
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    • 2022-08-03
    • 1970-01-01
    相关资源
    最近更新 更多