使用MATLAB编写在二维中实现牛顿方法的函数 [英] Using MATLAB to write a function that implements Newton's method in two dimensions

查看:557
本文介绍了使用MATLAB编写在二维中实现牛顿方法的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个在二维上实现牛顿方法的函数,尽管这样做,我现在必须调整脚本,以便函数的输入参数在列向量中必须为f(x), f(x)的雅可比矩阵,初始猜测x0以及函数f(x)及其雅可比矩阵位于单独的.m文件中的容差.

I am trying to write a function that implements Newton's method in two dimensions and whilst I have done this, I have to now adjust my script so that the input parameters of my function must be f(x) in a column vector, the Jacobian matrix of f(x), the initial guess x0 and the tolerance where the function f(x) and its Jacobian matrix are in separate .m files.

作为我编写的实现牛顿方法的脚本的示例,我有:

As an example of a script I wrote that implements Newton's method, I have:

n=0;            %initialize iteration counter     
eps=1;          %initialize error     
x=[1;1];        %set starting value

%Computation loop     
while eps>1e-10&n<100 
    g=[x(1)^2+x(2)^3-1;x(1)^4-x(2)^4+x(1)*x(2)];         %g(x)      
    eps=abs(g(1))+abs(g(2));                             %error     
    Jg=[2*x(1),3*x(2)^2;4*x(1)^3+x(2),-4*x(2)^3+x(1)];   %Jacobian     
    y=x-Jg\g;                                            %iterate     
    x=y;                                                 %update x     
    n=n+1;                                               %counter+1     
end 

n,x,eps       %display end values

因此,使用此脚本,我已经将函数和Jacobian矩阵实现到了实际的脚本中,而我正在努力研究如何真正使用所需的输入参数来创建脚本.

So with this script, I had implemented the function and the Jacobian matrix into the actual script and I am struggling to work out how I can actually create a script with the input parameters required.

谢谢!

推荐答案

如果您不介意,我想重组您的代码,以使其更具动态性和可读性.

If you don't mind, I'd like to restructure your code so that it is more dynamic and more user friendly to read.

让我们从一些预备开始.如果要使脚本真正具有动态性,那么我建议您使用Symbolic Math Toolbox.这样,您可以使用MATLAB来为您处理函数的派生类.首先,您需要使用syms命令,然后使用所需的任何变量.这告诉MATLAB您现在将把此变量视为符号"(即不是常量).让我们从一些基础知识开始:

Let's start with some preliminaries. If you want to make your script truly dynamic, then I would recommend that you use the Symbolic Math Toolbox. This way, you can use MATLAB to tackle derivatives of functions for you. You first need to use the syms command, followed by any variable you want. This tells MATLAB that you are now going to treat this variable as "symbolic" (i.e. not a constant). Let's start with some basics:

syms x;
y = 2*x^2 + 6*x + 3;
dy = diff(y); % Derivative with respect to x.  Should give 4*x + 6;
out = subs(y, 3); % The subs command will substitute all x's in y with the value 3
                  % This should give 2*(3^2) + 6*3 + 3 = 39

因为这是2D,所以我们将需要2D函数...因此,我们将xy定义为变量.调用subs命令的方式会稍有不同:

Because this is 2D, we're going to need 2D functions... so let's define x and y as variables. The way you call the subs command will be slightly different:

syms x, y; % Two variables now
z = 2*x*y^2 + 6*y + x;
dzx = diff(z, 'x'); % Differentiate with respect to x - Should give 2*y^2 + 1
dzy = diff(z, 'y'); % Differentiate with respect to y - Should give 4*x*y + 6
out = subs(z, {x, y}, [2, 3]); % For z, with variables x,y, substitute x = 2, y = 3
                               % Should give 56

另一件事...我们可以将方程式放入向量或矩阵中,并使用subs同时将xy的所有值代入每个方程式.

One more thing... we can place equations into vectors or matrices and use subs to simultaneously substitute all values of x and y into each equation.

syms x, y;
z1 = 3*x + 6*y + 3;
z2 = 3*y + 4*y + 4;
f = [z1; z2];
out = subs(f, {x,y}, [2, 3]); % Produces a 2 x 1 vector with [27; 25]

我们可以为矩阵做同样的事情,但是为了简洁起见,我不会向您展示如何做.我将遵循代码,然后您可以看到它.

We can do the same thing for matrices, but for brevity I won't show you how to do that. I will defer to the code and you can see it then.

现在我们已经建立了代码,让我们一次处理一个代码,以真正实现这种动态.您的函数需要初始猜测x0,函数f(x)作为列向量,Jacobian矩阵作为2 x 2矩阵以及公差tol.

Now that we have that established, let's tackle your code one piece at a time to truly make this dynamic. Your function requires the initial guess x0, the function f(x) as a column vector, the Jacobian matrix as a 2 x 2 matrix and the tolerance tol.

在运行脚本之前,您需要生成参数:

Before you run your script, you will need to generate your parameters:

syms x y; % Make x,y symbolic
f1 = x^2 + y^3 - 1; % Make your two equations (from your example)
f2 = x^4 - y^4 + x*y;
f = [f1; f2]; % f(x) vector

% Jacobian matrix
J = [diff(f1, 'x') diff(f1, 'y'); diff(f2, 'x') diff(f2, 'y')];

% Initial vector
x0 = [1; 1];

% Tolerance:
tol = 1e-10;

现在,将您的脚本变成一个函数:

Now, make your script into a function:

% To run in MATLAB, do: 
% [n, xout, tol] = Jacobian2D(f, J, x0, tol);
% disp('n = '); disp(n); disp('x = '); disp(xout); disp('tol = '); disp(tol);

function [n, xout, tol] = Jacobian2D(f, J, x0, tol)

% Just to be sure...
syms x, y;

% Initialize error
ep = 1; % Note: eps is a reserved keyword in MATLAB

% Initialize counter
n = 0;

% For the beginning of the loop
% Must transpose into a row vector as this is required by subs
xout = x0';

% Computation loop     
while ep > tol && n < 100 
   g = subs(f, {x,y}, xout);   %g(x)
   ep = abs(g(1)) + abs(g(2)); %error     
   Jg = subs(J, {x,y}, xout);  %Jacobian  
   yout = xout - Jg\g;         %iterate     
   xout = yout;                %update x     
   n = n + 1;                  %counter+1     
end

% Transpose and convert back to number representation
xout = double(xout');

我可能应该告诉你,当您使用Symbolic Math Toolbox进行计算时,数字的数据类型是sym对象.您可能希望将它们转换回实数,因此可以使用double将其转换回去.但是,如果您将它们保留为sym格式,则在您要查找的情况下,它会将数字显示为整洁的分数.如果需要小数点表示,则强制转换为double.

I should probably tell you that when you're doing computation using the Symbolic Math Toolbox, the data type of the numbers as you're calculating them are a sym object. You probably want to convert these back into real numbers and so you can use double to cast them back. However, if you leave them in the sym format, it displays your numbers as neat fractions if that's what you're looking for. Cast to double if you want the decimal point representation.

现在,当您运行此功能时,它应该会为您提供所需的内容.我尚未测试此代码,但我很确定这可以正常工作.

Now when you run this function, it should give you what you're looking for. I have not tested this code, but I'm pretty sure this will work.

很高兴回答您可能还有的其他问题.希望这会有所帮助.

Happy to answer any more questions you may have. Hope this helps.

干杯!

这篇关于使用MATLAB编写在二维中实现牛顿方法的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆