美文网首页
Matlab实现递归与迭代斐波那契数列的算法

Matlab实现递归与迭代斐波那契数列的算法

作者: 都灵的夏天_ | 来源:发表于2020-10-12 20:35 被阅读0次

    代码实现

    1. 创建递归实现的fibona.m

    function F = fibona( n )
    %fibona(0)=0
    %fibona(1)=1
    %fibona(n)=fibona(n-1)+fibona(n-2)
    %递归函数
    B(1)=1;
    B(2)=1;
    if(n>2)
        for i=3:n
            B(i)=fibona(i-1)+B(i-2);
        end
    end
    F=B(end);
    
    end
    
    

    2. 创建非递归实现的fibona1.m

    function F = fibona1( n )
    %fibona(0)=0
    %fibona(1)=1
    %非递归实现
    a=1;
    b=1;
    c=0;
    while n>2
        c=a+b;
        a=b;
        b=c;
        n=n-1;
    end
    F = c;
    

    3. 创建脚本绘图

    x = [];
    timer=[];
    x1 = [];
    timer1=[];
    n=20;
    %递归时间统计
    for i=1:n
        tic
        x(i)=fibona(i);
        timer(i) = toc;
    end
    %非递归时间统计
    for i =1:n
        tic
        x1(i)=fibona1(i);
        timer1(i)=toc;
    end
    plot(1:n,timer,1:n,timer1)
    xlabel('n值');
    ylabel('运行时间(/s)');
    title('斐波那契数列递归与非递归运行时间分析');
    legend('递归算法','非递归算法');
    

    实验结果

    递归与迭代时间分析

    相关文章

      网友评论

          本文标题:Matlab实现递归与迭代斐波那契数列的算法

          本文链接:https://www.haomeiwen.com/subject/ifvppktx.html