【问题标题】:Undefined argument when declaring function in Octave在 Octave 中声明函数时未定义的参数
【发布时间】:2017-02-16 07:50:08
【问题描述】:

我在尝试定义自己的随机生成器函数时得到未定义的变量/参数。

代码:

function result = myrand(n, t, p, d)
    a = 200 * t + p
    big_rand = a * n
    result = big_rand / 10**d
    return;
endfunction

mrand = myrand(5379, 0, 91, 4)

错误:

>> myrand
error: 't' undefined near line 2 column 15
error: called from
myrand at line 2 column 7

【问题讨论】:

  • 您的代码在 Octave 中适用于我。你在命令行上执行它吗?如果它是脚本的一部分(例如 foo.m),请确保第一行不以函数声明开头。一种常见的方法是在开头添加1;
  • 除了错误之外,这不是真正的random,甚至不是pseudo-random,因为您的“随机”数字只是(200*t*n+p*n)/(10*d),这是一个简单的四的一对一函数变量。
  • 你是把它保存为myrand.m然后 调用mrand = myrand(5379, 0, 91, 4),还是在命令行中同时执行函数声明和函数调用? (在这种情况下,MATLAB 会向您抛出错误“此环境中不允许函数声明”,不确定 Octave)
  • @Adriaan 是的,octave 允许内联函数定义,matlab 不允许。 (虽然显然这听起来像 2016b 会)

标签: function octave


【解决方案1】:

您不能使用 function 关键字启动脚本。 https://www.gnu.org/software/octave/doc/v4.0.1/Script-Files.html

这行得通:

disp("Running...")
function result = myrand(n, t, p, d)
     a = 200 * t + p
     big_rand = a * n
     result = big_rand / 10**d
     return;
endfunction

mrand = myrand(5379, 0, 91, 4) 

你应该得到:

warning: function 'myrand' defined within script file 'myrand.m'   
Running ...  
a =  91  
big_rand =  489489  
result =  48.949  
mrand =  48.949  

【讨论】:

  • 谢谢,但你知道它为什么会这样工作吗!??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-04
  • 2016-12-18
  • 1970-01-01
相关资源
最近更新 更多