[英]Fibonacci Sequence with Matlab using Loops(Iteration)
How do I write a Fibonacci function in Matlab using loops? 如何使用循环在Matlab中编写Fibonacci函数? Function must have two inputs.
函数必须有两个输入。
inputs: 1.a number to start the sequence 2.the number of terms to return (must be a positive integer (N)) 输入:1.开始序列的数字2.要返回的项数(必须为正整数(N))
Output: is a 1xN vector of the Fibonacci sequence. 输出:是斐波那契序列的1xN向量。
Conditions: If the initial term is 0 or 1, the second term will be 1. For any other number, the initial term will be repeated for the second number. 条件:如果初始项为0或1,则第二项将为1。对于其他任何数字,将对第二个数字重复初始项。
Thanks 谢谢
The definition of the Fibonacci sequence is the following: 斐波那契数列的定义如下:
The specifications for your function are rather odd, but nonetheless doable. 您的功能规格相当奇怪,但是仍然可行。 First you need to check if the initial term is 0 or 1. If that's the case, the second term will be 1. If anything else, the first two terms will be exactly the same as the initial term.
首先,您需要检查初始项是0还是1。如果是这种情况,第二项将是1。 You'll require a bunch of
if
statements first.... so something like this: 首先需要一堆
if
语句。
function out = fibonacci(initial_term, N)
if initial_term == 0 || initial_term == 1
second_num = 1;
else
second_num = initial_term;
end
if N == 1
out = initial_term;
elseif N == 2
out = [initial_term second_num];
else
out = zeros(1,N);
out(1:2) = [initial_term second_num];
for idx = 3 : N
out(idx) = out(idx-1) + out(idx-2);
end
end
end
The first if
statement checks to see if the initial term is either 0 or 1. If it is, the second number will be 1. If it isn't, the second number will be the same as the initial term. 第一个
if
语句检查初始项是0还是1。如果是,则第二个数字将是1。如果不是,则第二个数字将与初始项相同。
Next, we check to see what N
is. 接下来,我们检查一下
N
是多少。 If it's 1, then just return the initial term. 如果为1,则只需返回初始项。 If it's 2, then return an array of the initial term and second term.
如果为2,则返回初始项和第二项的数组。 If it's anything larger, then create an output array of size
N
where the first two elements are initialized like in the case of N = 2
, then we simply loop through and use the Fibonacci recurrence formula to populate each element in the output from index 3 and onwards. 如果更大,则创建一个大小为
N
的输出数组,其中前两个元素像N = 2
一样被初始化,然后我们简单地循环并使用Fibonacci递归公式填充索引3的输出中的每个元素及以后。
You can also write the for
loop as a while
loop as well. 您也可以将
for
循环编写for
while
循环。 Remember, a while
loop keeps iterating until the logical
condition that the while
loop checks becomes false
. 请记住,
while
循环会不断迭代, 直到 while
循环检查的logical
条件变为false
为止 。 As such, you would do: 因此,您将执行以下操作:
out = zeros(1,N);
out(1:2) = [initial_term second_num];
idx = 3;
while idx <= N
out(idx) = out(idx-1) + out(idx-2);
idx = idx + 1;
end
>> out = fibonacci(3, 6)
out =
3 3 6 9 15 24
>> out = fibonacci(0, 6)
out =
0 1 1 2 3 5
>> out = fibonacci(4, 10)
out =
4 4 8 12 20 32 52 84 136 220
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.