Matlab - 尾递归矢量和

时间:2016-05-23 00:54:43

标签: matlab recursion vector sum tail

我应该如何编写尾递归函数来计算向量的总和? 该函数需要2个输入参数:向量v和sum。 尾递归意味着函数的最后部分必须调用自身。

我有一个函数应该是什么样子的基本shell,但我不确定如何编写递归部分。

with streams:
str = 1234567890
str = 0987654321
with streams and manual operations:
str = 1234567890
str = 0987654321

对于空向量,该函数返回0的结果,如果向量的长度为1,则返回值v(1)。

1 个答案:

答案 0 :(得分:2)

您的解决方案有两个主要问题:

  1. 结果未累积 - 您只需调用vectorSum函数而不考虑先前调用的结果。
  2. 每次递归调用时问题的大小都不会减少。
  3. 有几种方法可以实现这种递归,我建议采用以下方法:

    function result = vectorSum(v)
    %takes a vector v and the returns the sum of all elements in the vector
    if length(v) == 0
        result = 0;
    else
        result = v(end) + vectorSum(v(1:end-1));
    end
    end
    
相关问题