Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run octave script file containing a function definition

Tags:

octave

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;
  else
    fibo = recfibo(n-1) + recfibo(n-2);
  endif
endfunction
disp(recfibo(5))

By inserting this code in an external file named for example file.m, and executing it through octave file.m an error occurs:

warning: function name 'recfibo' does not agree with function filename '/Users/admin/Google Drive/file.m' error: 'n' undefined near line 2 column 8 error: called from octave at line 2 column 3

How should I resolve this particular problem?

like image 1000
Davide Avatar asked Jan 02 '19 21:01

Davide


1 Answers

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.

like image 76
Cris Luengo Avatar answered Jan 04 '23 00:01

Cris Luengo