0

I am trying to use the Lagrange equation to output ma = -kx from the kinetic and potential energy of a mass on a spring, however I am encountering the errors below in both the following pieces of code. I understand that the error is stating that I cannot use a symbolic variable as the second argument of diff but in the MATLAB help documents, it states that for partial derivatives you write it in this format?

Method 1:

clear
clc

syms m K t x(t) x_dot(t)

T = 0.5 * m * x_dot^2
V = 0.5 * K * x^2

L = T - V

temp = diff(L, x_dot)

Method 2:

clear
clc

syms m K t x(t) x_dot

x_dot = diff(x)

T = 0.5 * m * x_dot^2
V = 0.5 * K * x^2

L = T - V

temp = diff(L, x_dot)

Error:

Error using sym/diff (line 26)
Arguments, except for the first, must not be symbolic functions.

If I remove the (t) from the symbolic initialiser for x, then the error goes away, but as far as I am aware, I will need x to be in terms of t later down the line as I’ll be differentiating x_dot with respect to t to get acceleration.

EDIT...

This is what I wanted to acheive, however I don't know if this can be done without introducing substitutions?

clear
clc

syms m K t x(t) v p

x_dot = diff(x);

T = 0.5 * m * x_dot^2;
V = 0.5 * K * x^2;

L_sym = T - V;

L1 = subs(L_sym, x_dot(t),v);
L = subs(L1, x(t), p);

temp = diff(L(t), v);

LHS = diff(subs(temp, v, x_dot(t)) / diff(t));
RHS = subs(diff(L(t), p), p, x(t));

eqn = LHS == RHS
4
  • You need x(t) so you can differentiate wrt t. But you also want to differentiate wrt x_dot. Why can’t you differentiate wrt t the same way you try to differentiate wrt x_dot? Oct 12, 2019 at 13:45
  • I'm unclear where your looking when you say "differentiate wrt x_dot" in the first two pieces of code, that is the line that causes issue, in the edit, the only part I can see differentiating wrt x_dot is LHS?
    – Ross Hanna
    Oct 12, 2019 at 21:00
  • When you do temp = diff(L, x_dot) in your first block of code, you differentiate L wrt x_dot. L depends on x. So you are computing the derivative of x wrt x_dot. Oct 13, 2019 at 0:08
  • Ah i see what you mean. I saw matlab displaying L(t) and didn't think. However this is still eluding me as i can't seem to tell matlab that i want it to differentiate wrt the differential of x(t) without an error
    – Ross Hanna
    Oct 13, 2019 at 6:00

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.