# Output argument 'answers' (and maybe others) not assigned during call to "..."

5 views (last 30 days)
James Metz on 15 Apr 2020
Commented: Adam Danz on 17 Apr 2020
I am trying to create a function that sums up all the values of the fibonacci series using only recursion, but I keep getting this error message...
Output argument "answer" (and maybe others) not
assigned during call to "sum_of_fibo>fibo".
Error in sum_of_fibo (line 2)
summa = sum(fibo(n:-1:0));
Here's my code...can someone help?
function summa = sum_of_fibo(n)
summa = sum(fibo(n:-1:0));
end
if n == 0
elseif n == 1
elseif n > 1
end
end

Image Analyst on 15 Apr 2020
If you pass in something like -1 or 0.4, answer will never get set to anything. You should set it to something, even if it's null, to avoid that error. Better yet, make an "else" for your if to handle cases where you're passing in values that are not positive integers or zero.
if n == 0
elseif n == 1
elseif n > 1
end
end
James Metz on 15 Apr 2020

Adam Danz on 15 Apr 2020
Edited: Adam Danz on 15 Apr 2020
Any time you write if... elseif... statements you should always include a final else statement, even if you think you've covered every possibility. The final else statement can either define a default value for answer or in can throw an error.
Example 1
if n == 0
elseif n == 1
elseif n > 1
else
answer = -1; % Default value
end
Example 2
if n == 0
elseif n == 1
elseif n > 1
else
error('''n'' must be greater or equal to 0.') % throw error
end
Adam Danz on 17 Apr 2020
Using the input [3 2 1 0] provided in a previous comment, the function above fails,
Out of memory. The likely cause is an infinite recursion within the program.
Error in sum_of_fibo (line 5)
summa = fibo(n) + jff(n-1);