Can I call a function from another function and not come back?
1 Comment
Accepted Answer
More Answers (1)
Hi @Gavin,
Your concerns about function management in MATLAB are valid, especially considering your experience with assembly language. Let me delve into the details of how MATLAB handles function calls, addressing your specific points about stack management and the necessity of additional functions. In MATLAB, when one function calls another, it indeed involves pushing the current execution context onto the call stack. However, MATLAB is designed to manage this process efficiently. Here’s a breakdown:
Stack Management: Unlike lower-level languages like assembly where stack overflow can be a significant concern due to manual control over the call stack, MATLAB abstracts these complexities. It automatically handles stack depth and memory allocation, allowing you to focus on your code's logic rather than low-level mechanics.
Recursion and Performance: While excessive recursion can lead to performance issues or stack overflow, this is typically a concern only when functions call themselves or each other in a deeply nested manner.
No Need for an Intermediary Function: Your initial thought about needing a third function may stem from a desire to simplify or control flow. However, as demonstrated in your examples, structuring functions hierarchically without an intermediary is perfectly acceptable and often preferable for clarity and maintainability.
Example Code Review
The example code snippets provided below illustrate how to structure function calls in MATLAB:
Main Function (mainFunction.m): This serves as the entry point, calling `secondaryFunction` and handling its output.
Secondary Function (secondaryFunction.m): It processes data and optionally calls another function (anotherFunction), demonstrating modularity.
Another Function (`anotherFunction.m): This further processes the data received from secondaryFunction.
So, you can see this hierarchical approach allows for clear data flow and logical separation of tasks.
Function Definitions
Main Function (mainFunction.m)
This is the entry point where you call your secondary function.
function mainFunction()
% Sample data to pass to the secondary function
inputData = 10; % Call the secondary function
result = secondaryFunction(inputData); % Display result
fprintf('Result from secondaryFunction: %d\n', result);
endSecondary Function (secondaryFunction.m)
This function performs a calculation and may call another function if needed.
function output = secondaryFunction(data)
% Perform some operation on the input data
processedData = data * 2; % Example operation % Optionally call another function
output = anotherFunction(processedData);
endAnother Function (anotherFunction.m)
This function takes processed data from the secondary function.
function output = anotherFunction(value)
% Further processing of value
output = value + 5; % Example operation
endStep-by-Step Instructions to Test
Create the Functions
- Open MATLAB and create three separate .m files named mainFunction.m, secondaryFunction.m, and anotherFunction.m.
Copy and Paste Code
- Copy the respective code snippets provided above into each file.
Run the Main Function
- In the MATLAB Command Window, type mainFunction() and press Enter.
Observe Output
You should see an output similar to:
Result from secondaryFunction: 25
This indicates that the flow through the functions is working correctly.
Please see attached.

If you still have any further questions, please let us know.
4 Comments
Hi @Image Analyst,
Thank you for your insightful comments regarding the function behavior. Your observation highlights an important distinction between optional function calls and recursion, which is critical for understanding how functions interact in MATLAB.
Optional Function Calls
In the initial statement, "I am running a function which at the end either returns or calls another function," it indeed suggests that the primary function has the option to either conclude its execution or delegate further processing to another function. This design pattern is common and allows for modular programming, enabling clearer separation of logic without necessarily introducing complexity through recursion.
Indication of Recursion
Conversely, the phrase "the first function gets called by the second function" suggests a recursive relationship where one function relies on another to complete its operations. If the second function calls back to the first, this can lead to a series of nested calls that may potentially lead to stack overflow if not managed properly.
Based on your observations, I would like to share my key considerations listed below.
Recursion Management: While MATLAB manages stack depth automatically, it's important to keep an eye on recursive depth when designing functions that call each other. A well-structured recursive approach can be efficient; however, excessive depth can cause performance issues or lead to stack overflow errors.
Function Hierarchy: As illustrated in the example code provided by me, organizing functions hierarchically without unnecessary intermediary functions can enhance code clarity and maintainability. Each function should ideally perform a distinct task and return results efficiently.
To clarify with an example: If functionA calls functionB, which then calls functionA again under certain conditions (e.g., for further processing), this constitutes recursion. However, if functionA simply calls functionB for data processing and completes its execution without invoking itself again, it remains a straightforward functional call.
So, distinguishing between these types of relationships is crucial for efficient MATLAB programming. I do respect your opinion and did edit my comments. Thanks for your help.
Categories
Find more on Variables in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!