1. 程式人生 > >MATLAB第十課:方程式求根

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