Run octave script file containing a function definition

前端 未结 2 1785
别跟我提以往
别跟我提以往 2021-01-14 09:54

I\'ve a very newbie octave question.
Running this code in octave console is working fine:

function fibo = recfibo(n)
  if ( n < 2 )
    fibo = n;
  el         


        
相关标签:
2条回答
  • 2021-01-14 10:01

    As stated in the answer provided by @CrisLuengo here you have created a function file instead of a script file and they are treated differently in Octave. Because it is a function file Octave executes it by calling the function it defines with no arguments and nargout = 0. So you will get an error that n is undefined.

    Another problem is that the function name 'recfibo' does not agree with function filename 'file'. In such cases Octave internally changes the name of the function to the name of the function file so the name is changed to 'file'. Therefor Octave and the function itself will forget the original function name and unfortunately the function cannot call itself recursively!

    I like the @CrisLuengo 's answer but I think the more idiomatic and preferable way is always using function files instead of script files, though the script file solution is the only solution that works in previous Octave versions (Octave 3.X).

    You can change your code to:

    function file
        disp(recfibo(5))
    endfunction
    function fibo = recfibo(n)
        if ( n < 2 )
            fibo = n;
        else
            fibo = recfibo(n-1) + recfibo(n-2);
        endif
    endfunction
    
    0 讨论(0)
  • 2021-01-14 10:09

    Add 1; as the first line of the file:

    1;
    
    function fibo = recfibo(n)
      if ( n < 2 )
        fibo = n;
      else
        fibo = recfibo(n-1) + recfibo(n-2);
      endif
    endfunction
    
    disp(recfibo(5))
    

    Any M-file that starts with a function definition is a function M-file, not a script M-file. By adding a meaningless statement to the top, you turn it into a script.


    In MATLAB (since fairly recently), a script M-file can define functions at the end of the script. There you'd put the disp line at the top of the file, and have the function block at the end, without any script lines after it. However, Octave requires functions to be defined before you use them, hence it has to come before the script line that uses the function. Octave allowed the definition of functions within a script file before MATLAB introduced that feature, hence their implementation is not compatible with that of MATLAB.

    0 讨论(0)
提交回复
热议问题