How to collect specific terms from an expression?

7 views (last 30 days)
Hello.
I have an expression like:
syms theta1 syms theta2 syms Dtheta1 syms Dtheta2 syms DDtheta1 syms DDtheta 2 syms g
t2 = 3*sin(theta2)*Dtheta1^2 + 3*DDtheta1 + 3*DDtheta2 + 3*g*cos(theta1+theta2) + 3*DDtheta1*cos(theta2)
I would like to be able to extract component terms from t2 (torque). For example, M21 would be the term that only multiplies DDtheta1. M22 would be the term that only multiplies DDtheta2. G would be the term that only multiplies g. And so on.
I tried to use the function collect, but I could not give values for the other variables to make them zero.
I was trying M21 = collect(t2, [DDtheta1 = 1, DDtheta2 = 0 , Dtheta1 = 0, Dtheta2 = 0, g = 0]) but MATLAB tells me it is wrong.
Does anyone know how I could do this? Thanks!

Accepted Answer

Star Strider
Star Strider on 16 May 2014
I’m not certain I understand.
Try this:
syms theta1 theta2 Dtheta1 Dtheta2 DDtheta1 DDtheta2 g M21 M22 G
% t2 = 3*sin(theta2)*Dtheta1^2 + 3*DDtheta1 + 3*DDtheta2 + 3*g*cos(theta1+theta2) + 3*DDtheta1*cos(theta2)
t2 = 3*sin(theta2)*Dtheta1^2 + M21*DDtheta1 + M22*DDtheta2 + G*g*cos(theta1+theta2) + 3*DDtheta1*cos(theta2)
M21 = solve(t2, M21)
M22 = solve(t2, M22)
G = solve(t2, G)
  6 Comments
Yurik Coelho
Yurik Coelho on 16 May 2014
That was exactly what I was looking for! Thank you!

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!