baby 發問時間: 電腦與網際網路程式設計 · 1 0 年前

matlab 方程式求根

好心的大大幫我看一下

最後一行,我想求方程式的根Dfalpha0 = -68+520*alpha0

但顯示錯誤,不知哪裡搞錯了

clc

clear

syms f Mx0 x1 x2 a b alpha0 falpha0 Dfalpha0 alpha0

function1 = input('please input a function :');

a1 = diff(function1,x1)

b1 = diff(function1,x2)

x1 = input('please input x1:')

x2 = input('please input x2:')

Mx0 = [x1;x2]

x11 = subs(a1,x1)

x22 = subs(b1,x2)

Mv0 = -[x11;x22]

x1 = x1-alpha0*x11

x2 = x2-alpha0*x22

falpha0 = subs(function1,{x1,x2},{sym('x1'),sym('x2')})

Dfalpha0 = diff(falpha0,alpha0)

alpha0 = roots(Dfalpha0)

執行

please input a function :(x1)^2+4*(x2)^2

a1 =

2*x1

b1 =

8*x2

please input x1:1

x1 =

1

please input x2:1

x2 =

1

Mx0 =

1

1

x11 =

2

x22 =

8

Mv0 =

-2

-8

x1 =

1-2*alpha0

x2 =

1-8*alpha0

falpha0 =

(1-2*alpha0)^2+4*(1-8*alpha0)^2

Dfalpha0 =

-68+520*alpha0

??? Error using ==> find

Function 'find' is not defined for values of class 'sym'.

Error in ==> C:\MATLAB6p5\toolbox\matlab\polyfun\roots.m

On line 22 ==> inz = find(c);

Error in ==> C:\MATLAB6p5\toolbox\new data\text1.m

On line 18 ==> alpha0 = roots(Dfalpha0)

已更新項目:

剛剛有用fzero試看看可以還是一樣

沒辦法滴說~

請大大在幫忙一下嚕~感激!!

1 個解答

評分
  • 老師
    Lv 7
    1 0 年前
    最佳解答

    roots指令不適用於 symbolic math

    2007-11-11 18:35:54 補充:

    而且 roots 指令只能用於求多項式的根

    非線性方程式求根 請用 fzero 指令

    2007-11-11 22:37:36 補充:

    fzero 也不能用在 symbolic math

    你要用 solve

    2007-11-11 22:59:12 補充:

    clc

    clear

    syms f Mx0 x1 x2 a b alpha0 falpha0 Dfalpha0 alpha0

    function1 = input('please input a function :');

    a1 = diff(function1,x1)

    b1 = diff(function1,x2)

    x1 = input('please input x1:')

    x2 = input('please input x2:')

    Mx0 = [x1;x2]

    x11 = subs(a1,x1)

    x22 = subs(b1,x2)

    Mv0 = -[x11;x22]

    x1 = x1-alpha0*x11

    x2 = x2-alpha0*x22

    falpha0 = subs(function1,{x1,x2},{sym('x1'),sym('x2')})

    Dfalpha0 = diff(falpha0,alpha0)

    alpha0 = solve(Dfalpha0)

    最後一行改成 solve 就可

    我存檔成為 find_root.m

    執行 >>find_root

    結果如下

    please input a function :x1^2+x2^2

    a1 =

    2*x1

    b1 =

    2*x2

    please input x1:2

    x1 =

    2

    please input x2:3

    x2 =

    3

    Mx0 =

    2

    3

    x11 =

    4

    x22 =

    6

    Mv0 =

    -4

    -6

    x1 =

    2-4*alpha0

    x2 =

    3-6*alpha0

    falpha0 =

    (2-4*alpha0)^2+(3-6*alpha0)^2

    Dfalpha0 =

    -52+104*alpha0

    alpha0 =

    1/2

    就如同我在意見中所說 roots 只適用於求多項式的根

    例如 求 x^3+3*x^2-2*x-10=0 利用 roots 求根

    >> p=[1,3,-2,-10];

    >> x=roots(p) 就可求出3個根

    或是利用 fzero 一次求一個根

    >> f=@(x) x^3+3*x^2-2*x-10;

    >> x1=fzero(f,0.1) %0.1是隨便猜的

    fzero 只能求出實數解 無法求出虛數解

    其實 fzero 使用了 bisection, Newton-Raphson, inverse quadratic interpolation 等方法 MathWorks公司已經最適化了

    詳細可以參考數值分析課本

還有問題?馬上發問,尋求解答。