recursive function that takes arr as an array input and prints out the product of array in matlab

Here's an example recursive function in Matlab that takes an array as an input and returns the product of all its elements:

main.m
function prod = recursiveProd(arr)
    if numel(arr) == 1 % base case: array has only one element
        prod = arr;
    else
        prod = arr(1) * recursiveProd(arr(2:end)); % Recursive case: multiply first element with product of the rest of the array
    end
end
269 chars
8 lines

You can call this function with an array like this:

main.m
arr = [1, 2, 3, 4, 5];
prod = recursiveProd(arr);
disp(prod); % Output: 120
76 chars
4 lines

This will output the product of all elements in the array arr, which is 1 x 2 x 3 x 4 x 5 = 120.

gistlibby LogSnag