recursive funtion of array without using sum in matlab

Here's a simple MATLAB function to recursively compute the sum of an array without using the built-in sum function:

main.m
function s = recursive_array_sum(arr, n)
% RECURSIVE_ARRAY_SUM Recursive array sum without using the built-in sum function
%   s = recursive_array_sum(arr, n) returns the sum s of the first n elements
%   of the input array arr using recursive calls to itself.

if n == 1
    s = arr(1);
else
    s = arr(n) + recursive_array_sum(arr, n-1);
end
345 chars
11 lines

The function takes two inputs: an array arr and an integer n specifying the number of elements to be summed. It returns the sum s computed recursively as follows: if there's only one element to be summed (i.e., n == 1), s is just that element; otherwise, s is the sum of the n-th element and the sum of the first n-1 elements (computed recursively).

You could test the function with an example array, like so:

main.m
a = [1 2 3 4 5];
n = length(a);
s = recursive_array_sum(a, n);
disp(s); % should output 15 (sum of 1+2+3+4+5)
110 chars
5 lines

gistlibby LogSnag