MATLAB求解单变量非线性方程的根可以使用fzero函数进行求解。
1.fzero函数
函数功能求解单变量非线性方程求解
语法
x = fzero(fun,x0)
x = fzero(fun,x0,options)
x = fzero(problem)
[x,fval,exitflag,output]=fzero()
说明
x = fzero(fun,x0) 尝试求出fun(x)=0的点 x。
此解是fun(x)变号的位置 - fzero 无法求函数(例如 x^2)的根。
x=fzero(fun,x0,options) 使用options修改求解过程。
x=fzero(problem) 对 problem 指定的求根问题求解。
[x,fval,exitflag,output]=fzero(___)返回 fun(x)(在 fval 输出中)、
对 fzero 停止的原因编码的 exitflag,以及包含有关求解过程的信息的输出结构体。
2.实例1
程序
clc;
clear all;
close all;
f=@(x) x.^2-1;
x0=-0.25:0.001:0.25;
x=x0; % 初始化
for ii=1:length(x0)
x(ii)=fzero(f,x0(ii));
end
plot(x0,x,'-o')
xlabel('初值');
ylabel('方程的根');
axis([-0.3,0.3,-1.5,1.5])
运行结果
3.实例2
程序
clc;
clear all;
close all;
syms x
%画出函数图像,对该函数有个大概的印象
t=-10:0.01:10;
y=sin(t).^2.*exp(-0.1*t)-0.5*abs(t);
plot(t,y)
hold on
plot([-10 10],[0 0],'k');
%从图像我们可以看出大概在x=[-2-1 0 1 2]附近的某个值时,y为零。下面我们就用fzero来具体求出零点。
f=@(t)sin(t).^2.*exp(-0.1*t)-0.5*abs(t)
%第一种方法使用arrayfun
%x=[-2 -1 0 1 2];
%arrayfun(@(x)fzero(f,x),x)
%第二种方法,分别带入
[x1 y]=fzero(f,-2)
[x2,y]=fzero(f,-1)
[x3,y]=fzero(f,0)
[x4,y]=fzero(f,1)
[x5,y]=fzero(f,2)
运行结果
x1 =
-2.0074
y =
2.2204e-16
x2 =
-0.5198
y =
-5.5511e-17
x3 =
0
y =
0
x4 =
0.5993
y =
0
x5 =
1.6738
y =
2.2204e-16
4.实例3
通过设置一些绘图函数绘制求解过程。定义函数和初始点。
程序
clc;
clear all;
close all;
fun = @(x)sin(cosh(x));
x0 = 1;
%通过设置包括绘图函数的选项检查求解过程。
options = optimset('PlotFcns',{@optimplotx,@optimplotfval});
x = fzero(fun,x0,options)
运行结果
x =
1.8115
5.实例4
求出 exp(-exp(-x)) = x 处的点,并显示有关求解过程的信息。
程序
clc;
clear all;
close all;
fun = @(x) exp(-exp(-x)) - x; % function
x0 = [0 1]; % initial interval
options = optimset('Display','iter'); % show iterations
[x fval exitflag output] = fzero(fun,x0,options)
运行结果
Func-count x f(x) Procedure
2 1 -0.307799 initial
3 0.544459 0.0153522 interpolation
4 0.566101 0.00070708 interpolation
5 0.567143 -1.40255e-08 interpolation
6 0.567143 1.50013e-12 interpolation
7 0.567143 0 interpolation
在区间 [0, 1] 中发现零
x =
0.5671
fval =
0
exitflag =
1
output =
包含以下字段的 struct:
intervaliterations: 0
iterations: 5
funcCount: 7
algorithm: 'bisection, interpolation'
message: '在区间 [0, 1] 中发现零'
本文内容来源于网络,仅供参考学习,如内容、图片有任何版权问题,请联系处理,24小时内删除。
作 者 | 郭志龙
编 辑 | 郭志龙
校 对 | 郭志龙