Recursion, How does it loop here?

  • Thread starter Thread starter Nano-Passion
  • Start date Start date
  • Tags Tags
    Loop Recursion
Click For Summary
SUMMARY

This discussion focuses on understanding recursion in programming, specifically through the example of finding the largest number in a vector using a recursive function. The provided MATLAB function, maxrec, demonstrates how recursion operates by breaking down the problem into smaller subproblems. The base case is defined for a vector of length one, while the recursive case compares the first element with the maximum of the remaining elements. This illustrates the circulatory nature of recursion, effectively functioning as a loop.

PREREQUISITES
  • Understanding of recursion in programming
  • Familiarity with MATLAB syntax and functions
  • Knowledge of base cases and recursive cases
  • Concept of vector manipulation in MATLAB
NEXT STEPS
  • Study the concept of recursion in depth with examples in various programming languages
  • Learn about base case and recursive case design patterns
  • Explore MATLAB's vector functions and their applications
  • Practice writing recursive functions for different algorithms
USEFUL FOR

This discussion is beneficial for students preparing for programming exams, particularly those focusing on recursion, as well as developers looking to strengthen their understanding of recursive algorithms in MATLAB.

Nano-Passion
Messages
1,291
Reaction score
0
I skipped all of my lectures since I usually like to understand things on my own but I am regretting it for recursion. 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
 
Technology news on Phys.org
You are at the wrong forums.

Next time go to lecture.
 

Similar threads

  • · Replies 16 ·
Replies
16
Views
3K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 11 ·
Replies
11
Views
1K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 5 ·
Replies
5
Views
12K
  • · Replies 11 ·
Replies
11
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K