- #1
Nano-Passion
- 1,291
- 0
I don't know why but I am finding it quite unintuitive and confusing. I have an exam coming tomorrow so I have to make sure that I understand it correctly.
I know that recursion functions as a loop due to its circulatory nature. However, I don't know exactly what is going on within the program to make it loop around here. Can someone clarify?
Find largest number using recursion.
function output = maxrec(vec)
% finds the largest number in a vector recursively.
% base case, if the vector has a length of 1, reuturn the single element.
% if not, return the larger of the 2 numbers
if length(vec) == 1
output = vec;
else
current = maxrec(vec(1,1));
next = maxrec(vec(1, 2:1:length(vec)));
if current > next
output = current;
else
output = next;
end
end
end
I know that recursion functions as a loop due to its circulatory nature. However, I don't know exactly what is going on within the program to make it loop around here. Can someone clarify?
Find largest number using recursion.
function output = maxrec(vec)
% finds the largest number in a vector recursively.
% base case, if the vector has a length of 1, reuturn the single element.
% if not, return the larger of the 2 numbers
if length(vec) == 1
output = vec;
else
current = maxrec(vec(1,1));
next = maxrec(vec(1, 2:1:length(vec)));
if current > next
output = current;
else
output = next;
end
end
end