Helped needed in Fibonacci Sequence code
3 ビュー (過去 30 日間)
古いコメントを表示
I already made a code that finds the nth term of a Fibonacci sequence (Fn) using a recursive function but I need help updating this code to also output how many times the recursive sequence ran.
As of right now, the code I have to find the nth term is: (where n=2 and n=1 are the base conditions that tells the recursive function to stop)
function[F_n] = Fibonacci(n)
if n == 2
F_n = 1;
elseif n == 1
F_n = 0;
else
F_n = Fibonacci(n-1) + Fibonacci(n-2);
end
end
0 件のコメント
採用された回答
Darshan Sen
2019 年 11 月 21 日
Hello Cici. We can solve this by introducing another variable count into the function as shown below.
function[F_n, count] = Fibonacci(n, count)
count = 1;
if n == 2
F_n = 1;
elseif n == 1
F_n = 0;
else
[F_n_1, count_1] = Fibonacci(n-1);
[F_n_2, count_2] = Fibonacci(n-2);
F_n = F_n_1 + F_n_2;
count = count + count_1 + count_2;
end
end
Now your function returns both the Fibonacci number as well as the number of times the function was called.
You may capture only the count in variable ans using this code snippet for the desired value of n.
[~, ans] = Fibonacci(n);
Hope this helps. :)
その他の回答 (1 件)
Joe
2024 年 9 月 23 日
Here’s a simple MATLAB code to generate the Fibonacci sequence:
function fibSequence = fibonacci(n)
% Initialize the first two Fibonacci numbers
fibSequence = zeros(1, n); % Preallocate for speed
fibSequence(1) = 0;
if n > 1
fibSequence(2) = 1;
end
% Generate the Fibonacci sequence
for i = 3:n
fibSequence(i) = fibSequence(i-1) + fibSequence(i-2);
end
end
You can call this function with the desired number of terms, for example:
result = fibonacci(10);
disp(result);
If you need further assistance with MATLAB coding, consider reaching out to Matlab Assignment Experts. They provide expert help, guaranteeing perfect grades with a 100% refund policy if you're not satisfied.
For quick support, contact them via WhatsApp at +1 (315) 557-6473. You can also email them at info@matlabassignmentexperts.com.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Financial Toolbox についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!