create an array that recursively creates the next element by reducing by a factor of 1/2 in matlab

main.m
function arr = createArray(n)
    % Base case
    if n == 1
        arr = [1];
    else
        % Create array of size n-1 recursively
        arr = createArray(n-1);
        % Compute next element by reducing factor by 1/2
        next = arr(n-1)/2;
        % Append next element to array
        arr = [arr, next];
    end
end

% Example usage: create an array of size 5
arr = createArray(5);
disp(arr);
406 chars
18 lines

This code defines a function createArray that takes an argument n for the size of the array to create. It recursively creates the array of size n-1, and then computes the next element by dividing the previous element by a factor of 1/2. The function returns the resulting array.

The example usage shows how to create an array of size 5 using this function, and displays the resulting array. The output should be:

main.m
1.0000    0.5000    0.2500    0.1250    0.0625
47 chars
2 lines

gistlibby LogSnag