4

是否可以从我在 matlab 中运行的程序函数中检索局部变量?即我想从代码中检索一个变量,该变量未出现在输出中。

提前致谢

4

3 回答 3

5

下面描述了添加到函数本身以使变量在本地范围之外可用的代码。当您无法更改功能时,从外部当然无需更改范围(这是有意的,正确的行为!!)。

肮脏的方式:

  • 全局变量

    global t
    t=2.468;
    
  • 对于标量、字符串、简单值:使用evalin分配给基础工作区中的变量:

    t=2.468;
    evalin('base', ['var_in_base=' num2str(t) ';']);
    
  • 任何其他变量,使用assignin

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

合适的方式:

  • 在调试期间检查它们
  • 如果您真的希望它们在本地范围之外,请将它们添加为输出变量!
于 2012-08-17T10:15:05.900 回答
1

看看声明函数。如果将局部变量作为返回值返回,则可以访问它们。如果不这样做,则无法从外部访问它们。

所以在

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

您可以访问 mean 和 stdev,但无法访问 n。

于 2012-08-17T10:14:19.827 回答
-2

I don't know matlab at all, but from programmer's logic that seems improper and impossible without hacking the code. That being said, through Google I saw this:

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

Base and Function Workspace

Not sure if this helps you at all, but it may clarify some points

于 2012-08-17T10:17:24.760 回答