如何在多个八度脚本之间共享全局变量?

发布于 2024-12-26 02:39:52 字数 140 浏览 3 评论 0原文

假设我有三个八度音阶脚本 am、bm、cm 和两个全局变量 x、y。是否可以以可以跨脚本共享的方式定义这些全局变量?例如在单独的包含文件中?

更一般地说,GNU Octave 中的全局变量如何工作?

Suppose I have three octave scripts a.m, b.m, c.m, and two global variables x, y. Is it possible to define these global variables in such a way that they can be shared across scripts? For example in a separate include file?

More Generally, how do global variables in GNU octave work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

凉城已无爱 2025-01-02 02:39:52

看来您必须将变量声明为全局变量,并且您还必须显式告诉 Octave 您引用的变量位于不同的(全局)范围内。

在library.m中,

global x = 1;

在main.m

function ret = foo()
    global x;
    5 * x;
endfunction

foo()中应该返回5

It seems you have to declare the variable global, and you also have to explicitly tell Octave that the variable you are referencing is in a different (global) scope.

in library.m

global x = 1;

in main.m

function ret = foo()
    global x;
    5 * x;
endfunction

foo() should return 5

子栖 2025-01-02 02:39:52

如何在 Octave 中使用全局变量:

创建一个名为 tmp.m 的文件并将以下代码放入其中。

global x;   %make a global variable called x
x = 5;       %assign 5 to your global variable
tmp2();     %invoke another function

创建另一个名为 tmp2.m 的文件,并将以下代码放入其中:

function tmp2()
  %the following line is not optional, it tells this function go go out and get
  %the global variable, otherwise, x will not be available.
  global x 
  x
end

当您像这样运行上面的代码时:

octave tmp.m

您将得到以下输出:

x =  5

全局变量 x 被保留在 tmp.m 中并在 tmp2.m 中检索

How to use global Variables in Octave:

Make a file called tmp.m and put the following code in it.

global x;   %make a global variable called x
x = 5;       %assign 5 to your global variable
tmp2();     %invoke another function

Make another file called tmp2.m and put the following code in there:

function tmp2()
  %the following line is not optional, it tells this function go go out and get
  %the global variable, otherwise, x will not be available.
  global x 
  x
end

When you run the above code like this:

octave tmp.m

You get this output:

x =  5

The global variable x was preserved in tmp.m and retrieved in tmp2.m

谈下烟灰 2025-01-02 02:39:52

类似于:

一个带有全局变量 globals.m 的文件,其中:

global my_global = 100;

并且只需在每个文件中使用 source 。例如:

source globals.m

global my_global

printf("%d\n", my_global);

Something like:

A file with global variables globals.m with:

global my_global = 100;

And just use source inside each file. For example:

source globals.m

global my_global

printf("%d\n", my_global);
仙气飘飘 2025-01-02 02:39:52

不确定这是最好的解决方案,但我最终创建了一个包装脚本,从中调用所有其他脚本。我将全局变量放入包装脚本中

Not sure this is the best solution, but I ended up creating a wrapper script, from which all the other scripts are called. I put my globals inside that wrapper script

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文