Here's an implementation of the rec_max
function in MATLAB:
main.m515 chars19 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