MATLAB第十课:方程式求根

目标

  • 符号方法
  • 数字根求解
  • 递归方程

问题描述:

假设有一个数学函数f(x0),想要找到一个x0,使得f(x0) = 0;

例如,函数

 使用MATLAB求解这个方程的方法

  • 解析法
  • 图解法
  • 数值解

一、符号方法

Symbolic Root Finding Approach(符号寻根方法):

  • 符号方法使用符号变量
  • 执行数学方法在符号上,不在数字上
  • 使用sym和syms创建符号变量
% 方法一:syms
>> syms x
>> x + x + x
 
ans =
 
3*x


% 方法2:sym
>> x = sym('x');
>> x + x + x
 
ans =
 
3*x

Symbolic Root Finding: solve()

>> syms x
>> y = x*sin(x)-x;
>> solve(y, x)
 
ans =
 
    0
 pi/2

Solving Multiple Equations

>> syms x y
>> eq1 = x - 2*y - 5;
>> eq2 = x + y - 6;
>> A = solve(eq1, eq2, x, y)

A = 

    x: [1x1 sym]
    y: [1x1 sym]

>> A.x
 
ans =
 
17/3
 
>> A.y
 
ans =
 
1/3

Solving Equations Expressed in Symbols

MATLAB总是以x为未知数。 

>> syms x a b
>> solve('a*x^2-b')

ans =
 
  b^(1/2)/a^(1/2)
 -b^(1/2)/a^(1/2)
 

我们让b为未知数。

syms x a b 
solve('a*x^2-b', 'b')

ans =
 
a*x^2

Symbolic Differentiation: diff()

>> syms x
>> y = 4*x^5;
>> yprime = diff(y)
 
yprime =
 
20*x^4

Symbolic Integration: 

>> syms x;
>> y = x^2*exp(x);
>> z = int(y);
>> z = z - subs(z, x, 0)
 
z =
 
exp(x)*(x^2 - 2*x + 2) - 2

符号方法和数值方法的区别:

二、数字根求解 

Using Function Handles

fsolve():

>> f2 = @(x)(1.2*x+0.3+x*sin(x));
>> fsolve(f2, 0)

ans =

   -0.3500

f2:A function handle
0:Initial guess

fzero():

注意:fzero只能解决函数穿过x轴的函数的解。不穿过x轴的函数,不能使用fzero函数求解。

>> f = @(x)x.^2;
>> fzero(f,0.1)

ans =

   NaN

>> fsolve(f,0)


ans =

     0


Finding Roots of Polynomials: roots()

>> roots([1 -3.5 2.75 2.125 -3.875 1.25])

ans =

   2.0000 + 0.0000i
  -1.0000 + 0.0000i
   1.0000 + 0.5000i
   1.0000 - 0.5000i
   0.5000 + 0.0000i

Numeric Root Finding Methods

包围方法:从包含根的间隔开始

包围方法的思想:就是最小二乘法。

算法的流程:

开放方法:Newton-Raphson方法

算法流程:

比较:

Recursive Functions

递归函数:递归思想是很重要的思想,可以上网查一些资料弄清楚

Factorial Recursive Function:因子递归函数

  • 该功能包括递归案例和基本案例
  • 该功能到达基本情况时停止
function output = fact(n) 
% fact recursively finds n! 
if n==1 
    output = 1; 
else 
    output = n * fact(n-1); 
end 
end

猜你喜欢

转载自blog.csdn.net/gyt15663668337/article/details/83443900