Matlab符號計算求導與化簡

依託於Maple的符號計算引擎,Matlab可以完成高等數學中幾乎一切符號計算。這裏簡單記錄一下蔡自興《機器人學》第三版中第四章的雙連桿的動能推導過程。

在書本上我們已知的信息是:

x2=d1sinθ1+d2sin(θ1+θ2)
y2=d1cosθ1d2cos(θ1+θ2)
v22=x˙2+y˙2

其中 θi(i=1,2) 是時間的函數,我們通過演算可以得到與書中一樣的不錯的表達式:

v22=d21θ1˙2+d22(θ2˙2+2θ1˙θ2˙+θ2˙2)+2d1d2cosθ2(θ1˙2+θ1˙θ2˙)

下面就以這個表達式爲目標,探索如何利用Matlab進行帶有導數的表達式的運算和化簡

clc,clear,close all
syms th1(t) th2(t) d1 d2 Dth1 Dth2

x2 = d1*sin(th1) + d2*sin(th1 + th2);
y2 = -d1*cos(th1) - d2*cos(th1 + th2);
v22 = diff(x2)^2 + diff(y2)^2

v22 指的是 v22 ,上述代碼的輸出結果爲:

v22(t) =

(d2*cos(th1(t) + th2(t))*(diff(th1(t), t) + diff(th2(t), t)) + d1*cos(th1(t))*diff(th1(t), t))^2 + (d2*sin(th1(t) + th2(t))*(diff(th1(t), t) + diff(th2(t), t)) + d1*sin(th1(t))*diff(th1(t), t))^2

簡化表達式

這個結果顯然不是我們想要的,下面逐步進行變換化簡

  1. 用變量 Dth1Dth2 替換 diff(th1(t), t)diff(th2(t), t) ,簡化表達式

    v22_pretty = subs(v22,[diff(th1(t), t) diff(th2(t), t)],[Dth1 Dth2])
    
    v22_pretty(t) =
    
    (d2*cos(th1(t) + th2(t))*(Dth1 + Dth2) + Dth1*d1*cos(th1(t)))^2 + (d2*sin(th1(t) + th2(t))*(Dth1 + Dth2) + Dth1*d1*sin(th1(t)))^2
  2. collect 函數按照 d1 的降冪次合併同類項

    v22_collect1 = collect(v22_pretty,d1)
    
    v22_collect1(t) =
    
    (Dth1^2*cos(th1(t))^2 + Dth1^2*sin(th1(t))^2)*d1^2 + (2*Dth1*d2*cos(th1(t))*cos(th1(t) + th2(t))*(Dth1 + Dth2) + 2*Dth1*d2*sin(th1(t))*sin(th1(t) + th2(t))*(Dth1 + Dth2))*d1 + d2^2*cos(th1(t) + th2(t))^2*(Dth1 + Dth2)^2 + d2^2*sin(th1(t) + th2(t))^2*(Dth1 + Dth2)^2
  3. 表達式中出現了 cos2θ+sin2θ 的表達式沒有進行化簡,下面用 simplify 函數進行化簡

    v22_simplify = simplify(v22_collect1)
    
    v22_simplify(t) =
    
    Dth1^2*d1^2 + 2*cos(th2(t))*Dth1^2*d1*d2 + Dth1^2*d2^2 + 2*cos(th2(t))*Dth1*Dth2*d1*d2 + 2*Dth1*Dth2*d2^2 + Dth2^2*d2^2
  4. collect 依照 [d1 d2] 降冪次合併同類項

    v22_collect2 = collect(v22_simplify,[d1 d2])
    
    v22_collect2(t) =
    
    Dth1^2*d1^2 + (2*cos(th2(t))*Dth1^2 + 2*Dth2*cos(th2(t))*Dth1)*d1*d2 + (Dth1^2 + 2*Dth1*Dth2 + Dth2^2)*d2^2
  5. 上面的表達式中,還有 cosθ2 沒有化簡

    v22_collect3 = collect(v22_collect2,cos(th2(t)))
    
    v22_collect3(t) =
    
    d1*d2*(2*Dth1^2 + 2*Dth2*Dth1)*cos(th2(t)) + (Dth1^2 + 2*Dth1*Dth2 + Dth2^2)*d2^2 + Dth1^2*d1^2

4 和5與下面的語句等價

collect(expr,[d1 d2 cos(th2(t))])

最後得到了文章伊始的表達式

後記

在已知結果情況下,省去探索的步驟,1-5的語句可以直接化簡爲:

v22_pretty = subs(v22,[diff(th1(t), t) diff(th2(t), t)],[Dth1 Dth2]);
v22_simplify = simplify(v22_pretty);
v22_collcet = collect(v22_simplify,[d1 d2 cos(th2(t))]);

依照一般的習慣,表達式的化簡多依賴於 simplifycollect ,像類似 expand (展開) horner (嵌套) 等函數通常是我們不希望遇到的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章