reverse a character array using recursion in matlab

main.m
% Define a function that takes a character array as input and returns the reversed array
function reversedArray = reverseArray(inputArray)
 
    if isempty(inputArray) % Base condition, return empty array when input is empty
        reversedArray = [];
    else
        firstChar = inputArray(1); % Get the first character of the array
        restOfArray = inputArray(2:end); % Get the rest of the array
        reversedRest = reverseArray(restOfArray); % Recursively reverse rest of the array
 
        % Concatenate the first character and reversed rest of the array
        reversedArray = [reversedRest, firstChar];
    end
end
633 chars
15 lines

You can call the function by passing a character array as input and it will return the reversed array. Here's an example:

main.m
inputArray = 'hello';
reversedArray = reverseArray(inputArray);
disp(reversedArray); % Output: olleh
101 chars
4 lines

gistlibby LogSnag