matlab - 使工作区中的matlab变量成为全局变量

标签 matlab function global-variables global

在工作区中我制作了一个矩阵。

enter image description here

现在我可以访问脚本中的变量了。就像 Variable(2) 将返回 4。

但是在像这样的函数里面

function y= getvariable(x)

y=Variable(x)
end

我收到错误

   y=getvariable(2)
    ??? Undefined function or method 'Variable' for input
    arguments of type 'double'.

    Error in ==> getvariable at 3
    y=Variable(x)

那么如何使 Variable 矩阵成为全局矩阵,以便我可以通过任何函数访问它?

最佳答案

尽管您可以使用全局变量

>> global Variable = rand(50,12);

...

function y = getvariable(x)

     % Always needed
     global Variable;

     % Here ya go
     y = Variable;

end

MUCH 更好的选择是使用

function x = getvariable(x)
     % no body needed    
end

你称之为

>> y = getvariable(Variable);

(当然,对于这个人为的例子,这将等于

>> y = Variable;

)

虽然全局变量有一些合法的用例,但一般来说,它们往往会使您的代码变得面条化,使代码更容易出错并且更难调试。 Have a read关于这个问题。

关于matlab - 使工作区中的matlab变量成为全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18638098/

相关文章:

python - Python 中 yield 关键字的 Matlab 等价物是什么?

使用 GUIDE : Want to dynamically update graphs 的 Matlab GUI

matlab - 在 matlab 中使用带有 ar 函数的 crossval 函数的例子?

matlab - 代码生成和标量结构参数

javascript - 将字符串作为函数执行

javascript - 函数不会更新变量

javascript - 在另一个范围内运行函数

function - 是否可以根据函数的输入值改变函数的返回类型注释?

c - Lua 在 C 中共享 upvalue 示例

c - 在 C 中打印 0 到 1,000,000 之间的素数