Here's a simple MATLAB function to recursively compute the sum of an array without using the built-in sum
function:
main.m345 chars11 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.m110 chars5 lines
gistlibby LogSnag