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

10 次查看(过去 30 天)
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 个评论
Image Analyst
Image Analyst 2024-9-22
"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.

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2024-9-22
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

更多回答(1 个)

Umar
Umar 2024-9-23
编辑:Umar 2024-9-23

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 个评论
Gavin
Gavin 2024-9-23
编辑:Gavin 2024-9-23
@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 2024-9-24
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by