【问题标题】:Fibonacci matrix using loops of matlab使用matlab循环的斐波那契矩阵
【发布时间】:2021-06-02 06:52:58
【问题描述】:

我想创建一个斐波那契数列的 MxN 矩阵。

我的 Matlab 函数应该采用两个整数,即 M 和 N,并返回斐波那契数列的二维数组,如

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

我只能创建 1 行矩阵

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

提前致谢。

【问题讨论】:

    标签: matlab loops nested-loops fibonacci


    【解决方案1】:

    如果您想用双循环构建矩阵,那么在完成第一行之后,您需要准备下一行,以便可以使用与第一行相同的方法来完成斐波那契计算。这种“准备”包括将当前行的第 2 个和第 3 个元素复制到下一行的第 1 个和第 2 个位置。

    看起来像这样:

    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
    

    但是,如果您不是特别需要双循环,我会提出另一种构建该矩阵的方法。只需计算一次包含所有所需元素的斐波那契套件,然后将相关元素复制到最终矩阵的每一行中。

    这看起来像:

    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
    

    为了确保两个函数输出相同的结果:

    >> 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-23
      • 2016-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      • 1970-01-01
      相关资源
      最近更新 更多