Results 1 to 2 of 2

Math Help - matlab code asap thanks Fibonacci sequence

  1. #1
    Newbie
    Joined
    Oct 2009
    Posts
    11

    matlab code asap thanks Fibonacci sequence

    Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
    1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
    Find the sum of all the even-valued terms in the sequence which do not exceed four million.


    what is the matlab code



    I have no idea what to do i got this so far and i do not know if its right???




    f=zeros(1,4000000);
    f(1)=1;
    f(2)=1;
    for j= 3:4000000
    f(j)=f(j-1)+f(j-2);
    end
    sum(f<4000000)
    Follow Math Help Forum on Facebook and Google+

  2. #2
    Grand Panjandrum
    Joined
    Nov 2005
    From
    someplace
    Posts
    14,972
    Thanks
    4
    Quote Originally Posted by savni98 View Post
    Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
    1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
    Find the sum of all the even-valued terms in the sequence which do not exceed four million.


    what is the matlab code



    I have no idea what to do i got this so far and i do not know if its right???




    f=zeros(1,4000000);
    f(1)=1;
    f(2)=1;
    for j= 3:4000000
    f(j)=f(j-1)+f(j-2);
    end
    sum(f<4000000)
    First you are generating the numbers from the wrong starting point, you are told to use f(1)=1, f(2)=2, but no matter it works better starting with f(1)=1, f(2)=1.

    You don't need to store the numbers, and you have to sum every third one, the following may work (its untested):

    Code:
    a=1;b=1;
    
    sum=0;                %running total of the even Fib. numbers
    for idx=3:4000000     %loop over a sufficient range no get a Fib. number over 4000000
      n=a+b;              %next Fib number
      a=b;b=n;            %reset last two numbers for next trip arround loop
      if n>4000000        %exit loop if current number >4000000
        break
      end
      if mod(idx,3)==0    %if this is an even Fib number add so running total
        sum=sum+n;
      end
    end
    CB
    Follow Math Help Forum on Facebook and Google+

Similar Math Help Forum Discussions

  1. Matlab code
    Posted in the Math Software Forum
    Replies: 2
    Last Post: April 4th 2011, 02:18 AM
  2. Replies: 2
    Last Post: March 1st 2010, 11:57 AM
  3. MATLAB code
    Posted in the Calculus Forum
    Replies: 0
    Last Post: November 5th 2009, 05:44 AM
  4. Need MAtlab code
    Posted in the Math Software Forum
    Replies: 1
    Last Post: April 26th 2009, 09:57 PM
  5. need help with maple code asap
    Posted in the Math Software Forum
    Replies: 0
    Last Post: March 29th 2009, 12:43 AM

Search Tags


/mathhelpforum @mathhelpforum