How to get local variables?

Is it possible to get a local variable from a program function that I ran in Matlab? that is, I want to get a variable from the code that does not appear on the outputs.

Thank you in advance

+4
source share
3 answers

The following describes the code to add to the function itself to make this variable available outside the local scope. When you cannot change the function, there is nothing to do from outside to change the volume of the course (which is intended, the correct behavior!).

Dirty ways:

  • global variables

    global t t=2.468; 
  • For scalars, strings, simple values: assign variables in the base workspace using evalin :

     t=2.468; evalin('base', ['var_in_base=' num2str(t) ';']); 
  • Any other variable, use assignin :

     A=magic(20); assignin('base','A',A); 

The right way:

  • Inspect them during debugging.
  • If you really want them outside the local scope, add them as the output variable!
+5
source

See Declare Function . You can access local variables if you return them as return values. If you do not, you will not be able to access them from outside.

So in

 function [mean,stdev] = stat(x) n = length(x); mean = sum(x)/n; stdev = sqrt(sum((x-mean).^2/n)); 

You have access to the middle and stdev, but no access to n.

+1
source

I don’t know what matlab is, but from the programmer’s logic what seems wrong and impossible without hacking the code. At the same time, through Google, I saw this:

When you call a script from a function, the script uses the workspace of the function. Like local functions, nested functions have their own workspaces. However, these workspaces are unique in two important ways: Nested functions can receive and modify variables in the workspaces of functions that contain them. All variables in nested functions or functions containing them must be explicitly defined. That is, you cannot call a function or script that assigns values ​​to variables if these variables no longer exist in the workspace of the function.

Base and workspace <

Not sure if this will help at all, but may clarify some points.

-2
source

All Articles