Can I call a function from another function and not come back?

2 visualizzazioni (ultimi 30 giorni)
I am running a function which at the end either returns or calls another function.
Way back in the old days in assembler I'd do JuMP instead of JumpSubRoutine
Maybe it doesn't matter but since the first function gets called by the second function I did't want to blow up the stack.
Do I need a third one that alternately calls the others to fix this?
  1 Commento
Image Analyst
Image Analyst il 22 Set 2024
"I am running a function which at the end either returns or calls another function." <== OK, fine.
"Way back in the old days in assembler I'd do JuMP instead of JumpSubRoutine" <== OK, fine.
"Maybe it doesn't matter but since the first function gets called by the second function I did't want to blow up the stack." <== OK, fine, that doesn't happen.
"Do I need a third one that alternately calls the others to fix this?" No. There is nothing to "fix".
Not sure where your confusion lies.

Accedi per commentare.

Risposta accettata

Walter Roberson
Walter Roberson il 22 Set 2024
You have a small number of possibilities:
  • set(0,'Rec​ursionLimi​t',N) -- change the recusion limit
  • write a third function that alternates calling the other functions
  • rewrite the code so that it runs iteratively intead of recursively

Più risposte (1)

Umar
Umar il 23 Set 2024
Modificato: Umar il 23 Set 2024

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);
   end

Secondary 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);
   end

Another 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
   end

Step-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 Commenti
Gavin
Gavin il 23 Set 2024
Modificato: Gavin il 23 Set 2024
@Umar Thank you for such a thorough answer. This morning I was thinking about late night stupidity on my part.
I'm embarassed that I even asked. I've done a lot of programming in many languages since my assembler days on the 6502. Just had a late night BF.
I can obviously add a Main function that will handle the whole process of running a trial like this instead of chaining them. Note I am using Ap Designer so have to say (app) or app. for everything I do. I guess with app do % implicit app might confuse beginners? You have been helpful with my other questions so know more about my issues but for @Image Analyst and others reading this, here is what I will be doing:
% Don't take this too literally I'm just giving an example not my actual code
function DoSession(app)
% Prelim setup
% ...
for TrialNumber 1:size(trialTable,1)
StartTrial(app,TrialNumber);
ManageResults(app,TrialNumber);
end % Run the trials
DoEndOfSession(app);
end % function
Your explaination will be very helpful to others new to MATLAB. @Walter Roberson's short answer that I accepted above is probably all a more advanced user will need.
Again, thanks to you both for your continuing support. I think I finally have this thing working
Umar
Umar il 24 Set 2024
Hi @Gavin,
Thank you for your thoughtful response. I appreciate your candidness regarding your late-night reflections and understand that we all have moments of uncertainty, regardless of our experience level. Your approach to structuring the DoSession function seems well-considered, and I believe it will serve as a solid foundation for running trials effectively. Utilizing the app structure in App Designer is indeed crucial, and your example illustrates this clearly. It is great to hear that my previous explanations have been helpful, not only to you but potentially to others who may encounter similar challenges. If you have any further questions or need additional support as you continue refining your work, please don’t hesitate to reach out. Your progress is commendable, and I am here to assist in any way I can. Thank you once again for your kind words about our collaboration.

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti


Release

R2023b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by