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
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