フィルターのクリア

Fibonacci sequence, slightly different.

3 ビュー (過去 30 日間)
Bob Whiley
Bob Whiley 2015 年 2 月 19 日
編集済み: Bob Whiley 2015 年 2 月 19 日
I am trying to write a code for the fibonacci sequence, but instead of adding the the term to its previous one, I want a number to start with (say 4, my code input called begin) and its first two outputs would be 4. It would loop n times (say 7 for this example). The output would look like [4 4 8 12 16 20 24]. How could I generalize this. So far I have
if begin ~=1 || begin ~= 0
seq(1)=begin;
seq(2)=begin;
k=3;
while k <= n
seq(k)=seq(begin-1)+begin;
k =k+1;
end
end

採用された回答

James Tursa
James Tursa 2015 年 2 月 19 日
Looks like your indexing into seq is not quite right. Try this:
seq(k)=seq(k-1)+begin;
  1 件のコメント
Bob Whiley
Bob Whiley 2015 年 2 月 19 日
Perfect, thanks!

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

その他の回答 (3 件)

Titus Edelhofer
Titus Edelhofer 2015 年 2 月 19 日
Hi,
I don't see what this has to do with Fibonacci though ;-). But you don't need the loop, just do something like
seq = begin * [1 1:(n-1)];
Titus

Evan
Evan 2015 年 2 月 19 日
編集済み: Evan 2015 年 2 月 19 日
It seems to be quite close. You just need to make one small change. You should reference the seq variable using the index, k, not the begin variable:
begin = 4;
n = 5;
if begin ~=1 && begin ~= 0
seq(1)=begin;
seq(2)=begin;
k=3;
while k <= n
seq(k)=seq(k-1)+seq(k-2);
k = k+1;
end
end
Note that your example output isn't a fibonnaci sequence. Is this really what you want? If so, you could just make that array with:
begin = 4;
n = 5;
seq = [begin begin:begin:begin * n];

Bob Whiley
Bob Whiley 2015 年 2 月 19 日
編集済み: Bob Whiley 2015 年 2 月 19 日
If he beginning number were 0, how could I make it so the first index in the output vector is 0, then the sequence continues normally after. Like if n = 6, and begin = 0, how could I get the output [0 1 1 2 3 5]
What I have so far is
if begin == 0
seq(1)=1;
seq(2)=1;
k=3;
while k <= n
seq(k)=seq(k-1)+seq(k-2);
k=k+1;
end
end

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by