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

1 回表示 (過去 30 日間)
James Metz
James Metz 2020 年 4 月 15 日
コメント済み: Adam Danz 2020 年 4 月 17 日
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
function answer = fibo(n)
if n == 0
answer = 1;
elseif n == 1
answer = 1;
elseif n > 1
answer = fibo(n-1) + fibo(n-2);
end
end

採用された回答

Image Analyst
Image Analyst 2020 年 4 月 15 日
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.
function answer = fibo(n)
answer = []; % empty
if n == 0
answer = 1;
elseif n == 1
answer = 1;
elseif n > 1
answer = fibo(n-1) + fibo(n-2);
end
end

その他の回答 (1 件)

Adam Danz
Adam Danz 2020 年 4 月 15 日
編集済み: Adam Danz 2020 年 4 月 15 日
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
function answer = fibo(n)
if n == 0
answer = 1;
elseif n == 1
answer = 1;
elseif n > 1
answer = fibo(n-1) + fibo(n-2);
else
answer = -1; % Default value
end
Example 2
function answer = fibo(n)
if n == 0
answer = 1;
elseif n == 1
answer = 1;
elseif n > 1
answer = fibo(n-1) + fibo(n-2);
else
error('''n'' must be greater or equal to 0.') % throw error
end
  9 件のコメント
James Metz
James Metz 2020 年 4 月 15 日
Thanks for all your help!
I was able to get it using this code:
function summa = sum_of_fibo(n)
if n == 0
summa = 1;
else
summa = fibo(n) + sum_of_fibo(n-1);
end
end
function answer = fibo(n)
if n < 0
answer = [];
elseif n == 0
answer = 1;
elseif n == 1
answer = 1;
else
answer = fibo(n-1) + fibo(n-2);
end
end
I don't think it's the most effective/efficient way to get to the right answer because it takes quite a while to run, but it uses recursion which is what I was going for. Thanks again for all your help!
Adam Danz
Adam Danz 2020 年 4 月 17 日
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);

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by