How should I write a tail recursive function to compute the sum of a vector? The function takes 2 input arguments: a vector v and sum. Tail recursion means that the last part of the function must call itself.
I have a basic shell of what the function should look like, but I am unsure about how to write the recursive part.
function result = vectorSum(v,sum)
%takes a vector v and the returns the sum of all elements in the vector
if length(v) == 0
result = 0;
elseif length(v) == 1
result = v;
else
result = vectorSum(v,sum)
end
end
The function returns a result of 0 for an empty vector, and if the vector's length is 1 it returns the value v(1).
Your solution has two main problems:
The are several ways to implement this recursion, I suggest the following approach:
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