加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

matlab实现牛顿迭代法求解非线性方程组

(2013-05-13 09:56:00)
From: http://hi.baidu.com/aillieo/blog/item/0800e2a10ac9a59647106493.html
已知非线性方程组如下
3*x1-cos(x2*x3)-1/2=0
x1^2-81*(x2+0.1)^2+sin(x3)+1.06=0
exp(-x1*x2)+20*x3+(10*pi-3)/3=0
求解要求精度达到0.00001
————————————————————————————————
首先建立函数fun
储存方程组编程如下将fun.m保存到工作路径中:
function f=fun(x);
%定义非线性方程组如下
%变量x1 x2 x3
%函数f1 f2 f3
syms x1 x2 x3
f1=3*x1-cos(x2*x3)-1/2;
f2=x1^2-81*(x2+0.1)^2+sin(x3)+1.06;
f3=exp(-x1*x2)+20*x3+(10*pi-3)/3;
f=[f1 f2 f3];
————————————————————————————————
建立函数dfun
用来求方程组的雅克比矩阵将dfun.m保存到工作路径中:
function df=dfun(x);
%用来求解方程组的雅克比矩阵储存在dfun中
f=fun(x);
df=[diff(f,'x1');diff(f,'x2');diff(f,'x3')];
df=conj(df');
————————————————————————————————
编程牛顿法求解非线性方程组将newton.m保存到工作路径中:
function x=newton(x0,eps,N);
con=0;
%其中x0为迭代初值eps为精度要求N为最大迭代步数con用来记录结果是否收敛
for i=1:N;
    f=subs(fun(x0),{'x1' 'x2' 'x3'},{x0(1) x0(2) x0(3)});
    df=subs(dfun(x0),{'x1' 'x2' 'x3'},{x0(1) x0(2) x0(3)});
    x=x0-f/df;
    for j=1:length(x0);
        il(i,j)=x(j);
    end
    if norm(x-x0)
        con=1;
        break;
    end
    x0=x;
end
 
%以下是将迭代过程写入txt文档文件名为iteration.txt
fid=fopen('iteration.txt','w');
fprintf(fid,'iteration');
for j=1:length(x0)
    fprintf(fid,'         x%d',j);
end
for j=1:i
    fprintf(fid,'\nm     ',j);
    for k=1:length(x0)
        fprintf(fid,' .6f',il(j,k));
    end
end
if con==1
    fprintf(fid,'\n计算结果收敛!');
end
if con==0
    fprintf(fid,'\n迭代步数过多可能不收敛!');
end
fclose(fid);
————————————————————————————————
运行程序
在matlab中输入以下内容
newton([0.1 0.1 -0.1],0.00001,20)
————————————————————————————————
输出结果
ans =
 
    0.5000    0.0000   -0.5236
 
——————————————————————————————————————————————————
在iteration中查看迭代过程
 
iteration         x1         x2         x3
     1        0.490718   0.031238  -0.519661
     2        0.509011   0.003498  -0.521634
     3        0.500928   0.000756  -0.523391
     4        0.500227   0.000076  -0.523550
     5        0.500019   0.000018  -0.523594
     6        0.500005   0.000002  -0.523598
     7        0.500000   0.000000  -0.523599
计算结果收敛!

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有