Search code examples
matlabloopsnested-loopsfibonacci

Fibonacci matrix using loops of matlab


I want to create an MxN matrix of the Fibonacci series.

My Matlab function should take two integers that are M and N and return a two-dimensional array of Fibonacci series like

A =

1 1 2 3 5 8 13 21 34

1 2 3 5 8 13 21 34 55

2 3 5 8 13 21 34 55 89

3 5 8 13 21 34 55 89 144

5 8 13 21 34 55 89 144 233

8 13 21 34 55 89 144 233 377

I just could create 1 row of the matrix

function A = double_fibonacci(M,N)
A = ones(M,N);
for ii = 1:M
    for jj = 3:N
        A(ii,jj) = A(ii,jj-1) + A(ii,jj-2);
    end
end
end

Thanks in advance.


Solution

  • If you want to build your matrix with a double loop, then after you finish the first line, you need to prepare the next line so the fibonacci calculations can be done with the same method than for the first line. This "preparation" involve copying the 2nd and 3rd element of the current line into the 1st and 2nd position of the next line.

    This would look like this:

    function A = double_fibonacci_loop(M,N)
    A = ones(M,N);
    for ii = 1:M
        % build the line normally
        for jj = 3:N
            A(ii,jj) = A(ii,jj-1) + A(ii,jj-2);
        end
        % if we're not on the last line, we copy the 2nd and 3rd element of the
        % current line into the 1st and 2nd element of the next line, so the
        % fibonacci calculation can proceed as in the block above
        if ii<M
            A(ii+1,1:2) = A(ii,2:3) ;
        end
    end
    

    However, if you don't specifically need a double loop, I would propose another way to build that matrix. Just compute only once a Fibonacci suite with all the elements required, then copy the relevant elements in each line of your final matrix.

    This would look like:

    function A = double_fibonacci(M,N)
    
    %% Construct a single fibonacci suite with the required number of elements
    nElements = M+N-1 ;
    basefib = ones(1,nElements) ;
    for k=3:nElements
        basefib(k) = basefib(k-1) + basefib(k-2) ;
    end
    
    % After that block, basefib =
    % [ 1  1  2  3  5  8  13  21  34  55  89  144  233  377 ]
    
    %% Now dispatch the relevant elements in each line of your matrix
    A = ones(M,N);
    for k=1:M
        A(k,:) = basefib(k:k+N-1) ;
    end
    

    And just to make sure, both function output the same result:

    >> A = double_fibonacci(6,9)
    A =
         1     1     2     3     5     8    13    21    34
         1     2     3     5     8    13    21    34    55
         2     3     5     8    13    21    34    55    89
         3     5     8    13    21    34    55    89   144
         5     8    13    21    34    55    89   144   233
         8    13    21    34    55    89   144   233   377