write a recursive function rec_max(arr,n) to find the maximum of a given vector arr (of length n). don’t use the matlab function max. in matlab

Here's an implementation of the rec_max function in MATLAB:

main.m
function m = rec_max(arr, n)
% Recursive function to find maximum of a vector

% Base case: if vector has only one element, that element is the maximum
if n == 1
    m = arr(n);
% Recursive case: divide vector in two parts and recursively find maximum of each part
else
    m1 = rec_max(arr(1:floor(n/2)), floor(n/2));
    m2 = rec_max(arr(floor(n/2)+1:n), n - floor(n/2));
    % Compare the two maximums to get the maximum of the whole array
    if m1 > m2
        m = m1;
    else
        m = m2;
    end
end
end
515 chars
19 lines

This function takes as input a arr, a vector of length n, and returns the maximum value in the vector using recursion.

To explain how it works, the function is divided in two cases, the base case and the recursive case:

  • if n == 1: if the vector has only one element, then that element is the maximum, so we return it as the output of the function.
  • if n > 1: if the vector has multiple elements, we divide it in two parts, and recursively find the maximum of each part. We then compare the two maximums found, and return the maximum of the two as the output of the function.

The recursive part of the function is where the magic happens. In the recursive case, the vector is divided in two parts, arr(1:floor(n/2)) and arr(floor(n/2)+1:n), and two recursive calls to rec_max are made with these two parts as input, to find the maximum of each part. These calls will eventually reach the base case when each part has length 1, and return the maximum of each part. We then compare the two maximums found using an if statement, and return the maximum of the two as the output of the function.

gistlibby LogSnag