Info

This question is closed. Reopen it to edit or answer.

NEED HELP - Cannot call variable from function file back into main script

1 view (last 30 days)
I have created a seperate function matlab file to graph some ODEs, I then pick a x value and have it return me the y value of the ODE plot in that function file.
When I go back to the main script where I call my function file It wont let me call any of the variables from the function file. I have tried gloabl variables and everything else I can find on the internet plz help

Answers (1)

Walter Roberson
Walter Roberson on 22 Oct 2020
This is correct behaviour for MATLAB. All local variables are discarded when a function returns, with the following exceptions:
  1. variables declared as "persistent" retain copies between runs of the functions, but it can be difficult to get at those values from outside the function
  2. variables declared as "global" retain copies that can be accessed from anywhere that declares "global" with the same variable name. Note that declaring a variable global in one place does not make the value accessible everywhere else -- only places that also declare the variable global.
If you have values that you want to be accessible outside the function, you should return their values. Or you should use the debugger to stop in the function before it returns.
  3 Comments
Walter Roberson
Walter Roberson on 22 Oct 2020
Tyler Choate comments to me:
not at all trying to help me solve the issue, why even answer
Walter Roberson
Walter Roberson on 22 Oct 2020
Tyler, if the methods I discuss are not suitable for your purposes, then the solution is for you to get a job at Mathworks and convince them from inside to undertake a major design change to allow local variables to still be accessible after the function has exited.
It would be a major major design change. One that would break the semantics of all programming languages more advanced than BASIC. It would be very hard to get Mathworks to change this.
I would suggest to you that it would be much easier for you to use one of the strategies that I already posted:
  • return the values you need from the function; OR
  • put in a breakpoint in the debugger to examine the variables before the function exits; OR
  • use one of the several methods discussed in the link to share variables between workspaces.

Products

Community Treasure Hunt

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

Start Hunting!