依託於Maple的符號計算引擎,Matlab可以完成高等數學中幾乎一切符號計算。這裏簡單記錄一下蔡自興《機器人學》第三版中第四章的雙連桿的動能推導過程。
在書本上我們已知的信息是:
其中
下面就以這個表達式爲目標,探索如何利用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(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
簡化表達式
這個結果顯然不是我們想要的,下面逐步進行變換化簡
用變量
Dth1
和Dth2
替換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
用
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
表達式中出現了
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
用
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
上面的表達式中,還有
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))]);
依照一般的習慣,表達式的化簡多依賴於 simplify
和 collect
,像類似 expand
(展開) horner
(嵌套) 等函數通常是我們不希望遇到的。