求方程x2-3x+1=0的根
方法一:利用MATLAB多项式求根函数roots来求根
//建立多项式系数向量P
>>p=[1,-3,1];
//求多项式的根
>>x=roots(p)
x=
绘图:
//产生x向量,x的值从-5变化到5,步长为0.1
x=-5:0.1:5;
//求函数值向量y1
y1=x.*x - 3*x + 1;
//产生一个同x向量同大小的零向量,即x从-5到5,y恒为0的水平线
y2=zeros(size(x));
//绘制函数曲线
plot(x,y1,x,y2);
方法二:利用单变量非线性方程根的函数fzero,求方程在某个初始点附近的实根
//利用MATLAB的匿名函数,来定义f(x)
>>f=@(x) x*x - 3*x + 1;
//调用fzero函数,分别求f(x) = 0 ,在x=0.5和x=2.5附近的实根
>>x1= fzero(f,0.5)
x1 =
>>x2 = fzero(f,2.5)
x2=
方法三:利用最优工具箱中的方程求根函数fsolve
>>f=@(x) x*x - 3*x + 1;
//fsolve的第三个参数用于设置优化参数,可以调用optimset函数来完成,optimset函数中的'Display'选项为'off'表示不显示迭代的中间结果
>>x1 = fsolve(f,0.5,optimset('Display','off')
方法四:利用solve函数求方程的符号解,即求得的解是一个表达式
//定义一个符号变量x
>>syms x
//调用solve函数求根
>>x=solve(x^2-3*x+1)
x=
3/2 - 5^(1/2)/2
5^(1/2)/2 + 3/2
//通过调用eval函数可以将符号解转换为数值解
>>x=eval(x)
x=
0.3820
2.6180