Matlab:重复迭代直到满足条件

时间:2015-10-28 00:45:05

标签: matlab loops iteration

我正在尝试将Matlab学习为具有R背景的人。我为迭代编写了以下程序,我想重复这个程序直到达到指定的条件。我相信我拥有为Matlab编写的所有代码,除了迭代应该无限次重复直到条件满足的命令(如下所示)。

有人能告诉我如何将其翻译成Matlab语法吗?我认为我应该使用while循环,但我不确定,因为迭代应该继续,直到满足条件而不是在满足某些条件时继续。是否等同于?谢谢!

function xn = newton_v2(f,fd,x0,tol)

% newton iteration

xn = x0;
repeat{ %%% 'This is how I would begin the repeat command in R'

    % evaluate function and derivative
    fxn = feval(f,xn);
    fdxn = feval(fd,xn);

    % newton iteration step
    xnp1 = xn - fxn/fdxn;

        if(abs(xnp1 - xn)/abs(xnp1) < tol)
            xn<-xnp1
        end

    % update
    xn = xnp1;
} %%% 'This is how I would end the repeat command in R'
end

另外,如果您在我的Matlab代码中发现其他任何错误,请告诉我。

3 个答案:

答案 0 :(得分:0)

我对R语法不太满意,但你有两个选择1.在一个值数组中传递给matlab for循环并迭代它们。然后绘制图形以找到最佳解决方案并尝试从那里获得更精确2.在while循环上设置条件。我认为你正在寻找更多的while循环,所以你会把你的条件放在那里。它可能在计算上更重,但取决于功能。可能没问题。

答案 1 :(得分:0)

你的意思是for循环的语法?

如果您正在尝试创建Newton的方法,请参阅我自己的实现脚本

  • y是函数
  • x0 - 第一个初始值
  • n - xns的近似值

    function Xn = newtonsMethod (y,x0,n,startDomain,endDomain)
    
    %the tangent line at any point on the curve
    y1 = matlabFunction(diff(sym(y)));
    Xn = x0;
    x= linspace(startDomain,endDomain,1000);
    
    %recursive call for the newton formula
     for i = 1 : n
    
        %find the tangent line
        L =@(x)(y1(Xn).*(x-Xn)+y(Xn));
    
        %find the root
        Xn = Xn - (y(Xn)./y1(Xn));
    
    end
    end
    

这可能不是最好的方法。但它可能有所帮助!

答案 2 :(得分:0)

我使用while循环执行Newton方法虽然hamaney在回答中的递归版本很有趣。我通过将函数句柄,初始猜测和容差传递给函数来实现此目的。

function x1 = NewtonMethod(f,x,tol)
% dtol is calculated from eps based on the function handle...not shown
xi = f(x); % initial guess
dxi = (f(x+dtol) - f(x-dtol)) / (2 * dtol);
x1 = x - xi / dxi;
while (abs(x1 - x) < tol)
    x = x1;
    xi = f(x);
    dxi = (f(x+dtol) - f(x-dtol)) / (2 * dtol);
    x1 = x - xi / dxi;
end
end

这种方法存在问题。如果初始猜测条件不佳或函数无限制,则可能是无限循环。因此,我包含一个循环计数器,并且当该计数器达到maxSteps值时通常会中断。

添加无限循环保护看起来像这样。

xi = f(x); % initial guess
dxi = (f(x+dtol) - f(x-dtol)) / (2 * dtol);
x1 = x - xi / dxi;
loopCounter = 0;
while (abs(x1 - x) < tol)
    x = x1;
    xi = f(x);
    dxi = (f(x+dtol) - f(x-dtol)) / (2 * dtol);
    x1 = x - xi / dxi;
    loopCounter = loopCounter + 1;
    if loopCounter > maxSteps
        % include warning message
        break
    end
end   
相关问题