简体   繁体   English

倍频程函数定义错误

[英]Octave function definition error

I am trying to use octave for the first time and I want to create a function as follows: 我试图第一次使用八度,我想创建一个如下函数:

1;
 function test=calc(x)
         a=x^2;
         factorial(a)
 endfunction

 val = calc (3)

I saved this as calc.m and when I run it I get an error that variable x is not defined. 我将其保存为calc.m,运行它时出现错误,未定义变量x。

What am I doing wrong? 我究竟做错了什么?

Update: The original question I managed to get working but now I ended up with another problem. 更新:最初的问题我设法解决了,但是现在我遇到了另一个问题。 Please consider the following code: 请考虑以下代码:

init = 5.;
function val=prodval(x)
  global init;
  val=x+init^2;
endfunction
fin=prodval(3)

When I save the script as test.m and run it i get the following error: 当我将脚本另存为test.m并运行它时,出现以下错误:

>> test

error: for x^A, A must be a square matrix.  Use .^ for elementwise power.
error: called from
    prodval at line 5 column 6
    test at line 7 column 4

What exactly is going on here? 这到底是怎么回事? I do not see where I defined a matrix by mistake... I also realise that this may not be the best definition of a function but I am trying... 我看不到我在哪里错误定义了矩阵...我也意识到这可能不是函数的最佳定义,但是我正在尝试...

[UPDATE] [更新]

For each scope you want a global to be "visible" you have to declare it as global. 对于每个作用域,要使全局变量“可见”,必须将其声明为全局变量。 Reference 参考

global init = 5;
function val = prodval (x)
   global init;
   val = x + init^2;  
endfunction

fin=prodval(3)
fin =  28

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM