绘图循环二分法matlab

时间:2016-04-15 03:36:51

标签: matlab loops plot bisection

我在Matlab中有下一个脚本,它是二分法

function root = biseccion(f,a,b,epsilon, max)

if (f(a)*f(b) >= 0)
        disp('f(a) *f(b) >= 0');
        root = 'Can't find the root';
        return;
    else
        fprintf('Iter\t\t\ta\t\t\tb\t\t\tm\t\t\tf(a)\t\t\tf(b)\t\t\tf(m)\n');
        fprintf('=========\t\t ======\t\t ======\t\t ======\t\t   ======\t\t   ======\t\t   ======\n');
        m = (a + b)/2;
        if (abs(f(m)) <= epsilon)
            root = m;
            return;
        else
            Iter = 0;
            hold on;
            while (abs(f(m)) >= epsilon  || Iter == max)
                Iter = Iter + 1; 
                m = (a + b)/2;
                if(f(a)*f(m) > 0)
                    a = m;
                else
                    b = m;
                end

                fprintf('%3d',Iter);
                fprintf('%20.4f',a);
                fprintf('%12.4f',b);
                fprintf('%12.4f',m);
                fprintf('%14.4f',f(a));
                fprintf('%16.4f',f(b));
                fprintf('%16.4f',f(m));
                plot(f(m));
                fprintf('\n');
            end
            hold off;
            root = m;
            title('Plot of error')
            xlabel('Number of iterations')
            ylabel('Error')
            grid on;
        end
 end

我需要首先绘制函数(变量f),然后在不同的图像中绘制误差(f(m)),我尝试了一些但没有结果:/

1 个答案:

答案 0 :(得分:0)

解决:

 function root = biseccion(f,a,b,epsilon, max)

if (f(a)*f(b) >= 0)
        disp( f(a) *f(b) >= 0');
        root = 'Can't find root';
        return;
    else
        fprintf('Iterations\t\t\ta\t\t\tb\t\t\tm\t\t\tf(a)\t\t\tf(b)\t\t\tf(m)\n');
        fprintf('=========\t\t ======\t\t ======\t\t ======\t\t   ======\t\t   ======\t\t   ======\n');
        m = (a + b)/2;
        if (abs(f(m)) <= epsilon)
            root = m;
            return;
        else
            Iter = 0;
            figure
            hold on
            while (abs(f(m)) >= epsilon  && Iter < max)
                Iter = Iter + 1; 
                m = (a + b)/2;
                if(f(a)*f(m) > 0)
                    a = m;
                else
                    b = m;
                end   
                plot(Iter,f(m),'--gs',...
                'LineWidth',2,...
                'MarkerSize',10,...
                'MarkerEdgeColor','b',...
                'MarkerFaceColor',[0.5,0.5,0.5])
                fprintf('%3d',Iter);
                fprintf('%20.4f',a);
                fprintf('%12.4f',b);
                fprintf('%12.4f',m);
                fprintf('%14.4f',f(a));
                fprintf('%16.4f',f(b));
                fprintf('%16.4f',f(m));
                fprintf('\n');
            end
             root = m;
             title('Error graphic')
             xlabel('Iterations')
             ylabel('Error')
             grid on;
        end
 end