MATLAB: How to determine the order of a symbolic differential equation

differential equationsMATLABsymbolic

I'm writing a function that takes a differential equation in symbolic form as an argument and I want to determine the order of the equation in terms of certain variables.
Example 1 A first-order system:
syms t s y(t) u(t) R L
diff_eqn = R*y(t) + L*diff(y(t), t) == u(t); % differential equation
The order (w.r.t. y(t)) is 1.
Example 2 A second-order system:
syms t s y(t) u(t) omega_n z K
diff_eqn = 1/omega_n^2*diff(y(t), t, 2) + 2*z/omega_n*diff(y(t), t) + y(t) == K*u(t);
The order is 2.
I would also like to know the order w.r.t. u(t) if possible as well which in general might not be 0.

Best Answer

There doesn’t exist a direct function to determine the order of a differential equation. However, there is a workaround, and we can use the reduceDifferentialOrder and get newvars from where we can get the last element and see the occurrence of t and this is one plus than the order of equation. Refer to the following code:
syms x(t) y(t) f(t)
eqs = [diff(x(t),t,t) == diff(f(t),t,t,t), diff(y(t),t,t,t) == diff(f(t),t,t)];
vars = [x(t), y(t)];
[newEqs, newVars, R] = reduceDifferentialOrder(eqs, vars)
l = length(newVars);
s = string(newVars(l,1));
order_of_equation = count(s, 't') -1;