MATLAB: Sum by recursion without using sum of Matlab

MATLABrecursion

Question: "Write a function with header [S] = mySum(A) where A is a one-dimensional array, and S is the sum of all the elements of A. You can use recursion or iteration to solve the problem, but do not use MATLAB’s function sum." Answer (there is error)
function [S] = mySum(A)
% this program is the sum of all the elements of A
%A is a one dimention array
%get A
[n]=size(A);
if n==1
% base case.
S= A(1);
elseif n==2
%base case
S=A(1) + A(2);
else
%recusrive step
S = mySum(A(n-1)) + mySum(A(n-2));
end
end
Where is the error?

Best Answer

You are making this much more difficult than it needs to be. Think about how you would manually sum a vector. Then write that program in MATLAB.
So if the vector is:
v = [5 7 1 2 9];
in the first iteration, the sum ‘S’ is equal to ‘v(1)’. In the second iteration the sum ‘S’ is equal to ‘S+v(2)’, the third iteration ‘S+v(3)’, and so to the end of the vector.
I’ll let you take it from there.