matlab - Recursive Function to generate / print a Fibonacci series -
i trying create recursive function call method print fibonacci until specific location:
1 function f = fibonacci(n) 2 fprintf('the value %d\n', n) 3 if (n==1) 4 f(1) = 1; 5 return; 6 elseif (n == 2) 7 f(2) = 2; 8 else 9 f(n) = fibonacci(n-1) + fibonacci(n-2); 10 end 11 end
as per understanding fibonacci function called recursively until value of argument n passed 1. function stack rollback accordingly. when call function command:
>> fibonacci(4)
the value of n 4, line 9 execute like:
9 f(4) = fibonacci(3) + fibonacci(2);
now believe that first fibonacci(3) called - hence again fibonacci(3)
9 if(3) = fibonacci(2) + fibonacci(1);
the ifs in line number 3 , 6 take care.
but how fibonacci(2) + fibonacci(1) statement change to:
if(3) = 2 + 1;
i receiving below error , unable debug further resolve it:
>> fibonacci(4) value 4 value 3 value 2 value 1 in assignment a(i) = b, number of elements in b , must same. error in fibonacci (line 9) f(n) = fibonacci(n-1) + fibonacci(n-2); error in fibonacci (line 9) f(n) = fibonacci(n-1) + fibonacci(n-2);
please provide insight solution , parameter fibonacci function recursively called @ line number 9 first , consequently.
ex n = 4
f(n) = fibonacci(3) + fibonacci(2);
so matlab call fibonacci(3) or fibonacci(2) first?
shouldn't code thing below:
1 function f = fibonacci(n) 2 fprintf('the valus %d\n', n) 3 if (n==1) 4 f(1) = 1; 5 return f(1); 6 elseif (n == 2) 7 f(2) = 2; 8 return f(2); 9 else 10 f(n) = fibonacci(n-1) + fibonacci(n-2); 11 end 12 end
fibonacci(4) error: file: fibonacci.m line: 5 column: 12 unexpected matlab expression.
why return expression in function resulting in error?
try this:
function f = fibonacci(n) if (n==1) f= 1; elseif (n == 2) f = 2; else f = fibonacci(n-1) + fibonacci(n-2); end
note recursion (that evaluates each n once):
function f=fibonacci(n) f=additive(n,1,2); function a=additive(n,x0,x1) if(n==1) a=x0; else if(n==2) a=x1; else a=additive(n-1,x1,x0+x1); end end
Comments
Post a Comment